Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

JavaScript - JSON Parse & Stringify



In JavaScript, JSON.parse() and JSON.stringify() are two essential functions for working with JSON (JavaScript Object Notation) data. These functions allow you to convert data to and from JSON format, which is a popular data interchange format used for transmitting and storing data.

JSON.stringify()

This function converts a JavaScript object or value to a JSON string. It is useful when you need to serialize data to send it over a network or save it in a file.

Syntax:

javascript
JSON.stringify(value, replacer, space);
  • value: The value to convert to a JSON string.

  • replacer (optional): A function or array that can transform the results.

  • space (optional): A number or string used to control spacing in the output JSON string for readability.

Example:

javascript
const obj = { name: "Alice", age: 30, city: "Tokyo" };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{"name":"Alice","age":30,"city":"Tokyo"}'

// With pretty printing
const prettyJsonString = JSON.stringify(obj, null, 4);
console.log(prettyJsonString);
/*
Output:
{
    "name": "Alice",
    "age": 30,
    "city": "Tokyo"
}
*/

JSON.parse()

This function parses a JSON string and converts it to a JavaScript object or value. It is useful when you receive JSON data from a server or read it from a file and need to convert it into a usable JavaScript object.

Syntax:

javascript
JSON.parse(text, reviver);
  • text: The JSON string to parse.

  • reviver (optional): A function that can transform the parsed results.

Example:

javascript
const jsonString = '{"name":"Alice","age":30,"city":"Tokyo"}';
const obj = JSON.parse(jsonString);
console.log(obj); // Output: { name: 'Alice', age: 30, city: 'Tokyo' }

// Using reviver function
const objWithDate = JSON.parse('{"name":"Alice","birthDate":"1990-01-01T00:00:00Z"}', (key, value) => {
    if (key === "birthDate") {
        return new Date(value);
    }
    return value;
});
console.log(objWithDate);
/*
Output:
{
    name: 'Alice',
    birthDate: 1990-01-01T00:00:00.000Z
}
*/

Summary

  • JSON.stringify(): Converts JavaScript objects/values to JSON strings.

  • JSON.parse(): Converts JSON strings to JavaScript objects/values.

These functions are extremely useful for data interchange between clients and servers in web applications. If you have any specific scenarios or further questions about JSON.parse() and JSON.stringify(), let me know!




All rights reserved | Privacy Policy | Sitemap