Using JSON.stringify() for custom serialization of an object

Imagine there is an object called a with properties:

const a = {
  foo: 123,
  bar: 'example'
}

Now, this object is a part of another object called b like this:

const b = {
  a: a,
  anotherField: "example"
}

While working with TypeScript, these objects belong to the same class but it's not crucial.

When converting the b object to JSON, the desired string is:

{ a: 123, anotherField: "example" }

How can we instruct JSON.stringify() to format the a object in this way?

Perhaps something akin to the features available in Python could be useful.

Answer №1

In the context of a, you have the option to define the toJSON method.

When an object that is being converted to a string has a property called toJSON with a value that is a function, the toJSON() method can be used to customize the behavior of JSON stringification. Instead of serializing the object itself, the value returned by the toJSON() method will be serialized.

(source: MDN)

For instance:

class A {
  constructor(foo, bar) {
    this.foo = foo;
    this.bar = bar;
  }

  toJSON() {
    return this.foo;
  }
}

const a = new A(123, "some name");
const b = {
  a: a,
  anotherField: "example"
};

console.log(JSON.stringify(b)); // "{"a":123,"anotherField":"example"}"

Answer №2

To implement custom stringification while using the replacer during the stringify process, you can do the following:

 const result = JSON.stringify(b, (k, v) => v && v.stringify() || v);

This technique allows you to easily incorporate a personalized stringification for a like so:

 const a = {
   foo: 123,
   bar: 'example',
   stringify() { return this.foo; }
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide to swapping an element with a textarea element using javascript

My current project involves creating a user profile that includes a text box where users can describe themselves. I've already implemented a separate page for editing the profile, but now I want to add a feature where users can hover over their descri ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Change the WordPress Divi Builder nav bar to switch from transparent to white when scrolling or upon reaching a specific point on the page

Currently, I am in the process of revamping our company's WordPress website using the Divi Builder. For the past couple of days, I have been scouring the internet trying to find a solution that would allow the navigation bar to change CSS classes as t ...

When the start and end times are the same, the time picker is returning a null value

<input type="text" id="begin" class="form-control timepicker timepicker-no-seconds" name="start_event"> <input type="text" id="close" class="form-control timepicker timepicker-no-seconds" name="end_event"> The script for both is: $('#beg ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Having issues with jsonSerializer.Deserialize when it comes to handling unicode characters in c#

My issue involves deserializing a JSON object that contains Unicode data into a string array. It seems to work fine for English characters, but when I try using Chinese characters, it fails. JavaScriptSerializer jsonSerializer = new JavaScriptSerializer() ...

The error message "Adyencheckout is not a constructor" is popping up in my

Struggling to implement the Adyen dropin payment UI in NextJS and facing issues initializing the Adyen dropin component. Attempting to dynamically import Adyen web to avoid window is not defined error, but uncertain on how to use it as a constructor after ...

Updating reference value with a watcher using Vue 3 and the Composition API

I'm having trouble updating a ref within a watch function. My goal is to monitor changes in the length of an array, and if the new length is less than the old one, I want to update a specific ref called selectedTitle. setup() { const slots = useS ...

import PHP code to extract JSON data

I have been working on pulling JSON data into a PHP page that displays a list of products. When a product is clicked, it should take the user to a product detail page by adding its name to the URL. However, I am facing issues with getting the correct data ...

Assign a value to ng-model using JavaScript

Encountering an issue while working with JavaScript in AngularJS. There is a text field identified by id="longitude". <input type="text" data-ng-model="newwarehouse.longtitude" id="longitude"/> The value of this field is being set using JavaScript. ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

I am experiencing issues with my three.js script not functioning properly within the context of a

I have been working on implementing a raycaster function in my project that only activates when an entity is visible. To achieve this, I was advised to create a custom script for better control. I have set up all entities and their child entities to be in ...

Exploring the integration of angular-ui-select into an angular seed project

I set up a new project using the starter template from https://github.com/angular/angular-seed and now I'm attempting to integrate angular-ui-select for dropdown menus. I've added select.js and select.css files to my index.html as well as install ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

Creating a custom math formula using a combination of Javascript and PHP

Is it possible to apply a math formula from another variable or database? var x = 7; var formula = '+'; var y = 10; By this, I mean that the variables should output = 17 (7 + 10); How can we implement this formula using Javascript or PHP? ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...