JSON Stringify

JSON Stringify

When sending data to a web server, the data has to be perfectly formatted as a text string.

You cannot send raw, complex JavaScript objects directly over the HTTP network.


Using JSON.stringify()

To convert a JavaScript object into a valid JSON string, use the JSON.stringify() function.

This function safely serializes your objects and arrays, instantly preparing them for network transit!

All object keys are automatically wrapped in required double quotes during this process.


Stringifying Dates and Functions

If your object contains a Date, JSON.stringify() will automatically convert it into a string.

However, if your object contains a function, JSON.stringify() will completely remove the function!

JSON strictly forbids functions; you must convert functions to strings first if you absolutely must keep them.

JSON.stringify() Example:

let myObj = { name: "John", age: 30, city: "New York" };

// Converts the JS object into a JSON string let myJSON = JSON.stringify(myObj);

// The resulting string is ready to be sent to a server! console.log(myJSON);


Pretty Formatting

By adding additional parameters to the stringify function, you can format the string beautifully.

Passing JSON.stringify(obj, null, 2) adds line breaks and space indentation.

This makes reading massive API payloads incredibly easy during development and debugging!


Exercise 1 of 1

?

What happens if you try to use JSON.stringify() on a JavaScript object that contains a function?