What exactly happens behind the scenes when JSON.stringify() is called?

How does the replacer argument function extract keys and values from an object's value and map them to its key and value arguments in the JSON.stringify(value, replacer, space) method?

I have grasped that the key of the object becomes the key parameter of the replacer function and the value becomes the value parameter of this function.


let user = { name: "anup", age: 22 };
JSON.stringify(user, function(key, value) {
    if (typeof value === "string") { return undefined; }
    return value;
}, null);

In this code snippet, 'name' becomes the key of the replacer function and '"anup"' becomes the value of the replacer function. It is clear how this mapping works technically, but my question remains - how is this dynamic mapping achieved?

Typically, when we call a method, we pass arguments to that method during the method call, like so:


function a(c, d) {
    // logic
}
a(2, 3);

But in the stringify method, we are not explicitly passing anything to the replacer function or callback function. So, how exactly is this mapping process orchestrated?

As I am relatively new to the world of JavaScript, there are some concepts that I struggle to fully grasp. Any guidance you could provide on this matter would be greatly appreciated!

Answer №1

Exploring the Inner Workings of JSON.stringify()

While JSON.stringify() likely involves complex, optimized native code at a low level, let's imagine it as a standard JavaScript function for simplicity. The hypothetical function could be outlined like this:

 JSON.stringify = function(toStringify, replacer) {

To begin, this function would need to determine the nature of the variable toStringify, such as:

  if(typeof toStringify === "object") {

If it is an object, the code would proceed to iterate through its key/value pairs:

  for(let key in toStringify) {
    let value = toStringify[key];

The replacer function would then be invoked with these pairs:

   value = replacer(key, value);

Subsequently, a string representation would be constructed like so:

   result += `"${key}": ${JSON.stringify(value)}`;

Finally, the resulting string would be returned by the function.

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

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

Is there a way to trigger a function with ng-click in my AngularJS directive?

I am struggling to understand how to invoke a function from my directive using ng-click. Here is an example of my HTML: <div> <directive-name data="example"> <button class=btn btn-primary type="submit" ng-click="search()"> ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

Save Chrome's console log programmatically

Can anyone provide insights on how to use javascript or nodejs to automatically extract the contents of Chrome's console for saving it into a file or database? ...

Quickest method for deriving a boolean value from multiple boolean inputs

Within a document, the keys isOccupied and vacant are being destructured. const { isOccupied, vacant } = doc || {}; boolDetermination = (isOccupied, vacant) => { if (isOccupied && isOccupied === vacant) { < --- Return isOccupied value ...

The nested object was not found in the Gson return

Trying to figure out a basic implementation in my code. I have a json file that I need to read and convert into a Java object using gson. However, I'm encountering an issue where it returns null for nested objects. Json: { "results": { ...

Encounter a snag when attempting to upgrade to React version 16.10.2 while working with Ant Design Components - the error message reads: "

After upgrading to the latest React version 16.10.2, I encountered issues while using Ant Design Components. I specifically wanted to utilize the Title component from Typography. Here is an example of what I was trying to do: import { Typography } from & ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

`I am unable to insert an image into PrimeReact`

I am struggling to integrate images into the dashboard using primereact. Despite placing my photo folder in the public directory and entering the correct photo path, the image is not displaying on the page. I have attempted numerous methods but have been ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

What factors contribute to a one-hour discrepancy between two time stamps, deviating from the anticipated value?

Let's consider the dates '2022-04-01' and '2022-05-15'. When I calculated their deviation using Chrome devtools, here are the results: https://i.stack.imgur.com/tSZvk.png The calculated result is 3801600000. However, when my frie ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

What causes the inconsistency in results between the geocode API and Google Maps?

I am just starting to explore the world of google geocode API and would like to utilize the free version to retrieve map coordinates for nearby golf courses. I decided to begin with my home course: http://maps.google.com/maps/api/geocode/json?address=Karls ...

Path expression is not valid as it attempts to access an element

When attempting to modify a single element in an array, I encounter the error message Invalid path expression near attempt to access element. Interestingly, this issue only arises when the array is obtained from --rawInput. For instance: # input: [ 1, 0 ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs: In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com. The goal is to update the values in ng-repeat after clicking the copy button. ...

npm causing problems with babel-cli

While working on building a section of my library with Babel, I've encountered some issues when running Babel commands through npm. In my npm script named "build," the following commands are executed: { "prebuild": "rm -rf && mkdir dist", ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...