json

JSON in JavaScript

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between a server and a client.

Parsing JSON

Use JSON.parse() to convert a JSON string into an object:

      
        let jsonString = '{"name": "Alice", "age": 25}';
        let jsonObj = JSON.parse(jsonString);
        console.log(jsonObj.name); // Outputs: Alice
      
    

Stringifying JSON

Use JSON.stringify() to convert an object into a JSON string:

      
        let person = { name: "Alice", age: 25 };
        let jsonString = JSON.stringify(person);
        console.log(jsonString); // Outputs: '{"name":"Alice","age":25}'
      
    

Activity

Try It Yourself!

Create a JavaScript object and convert it into a JSON string. Then, convert the JSON string back into an object.

Quiz

Quick Quiz

  1. What does JSON.parse() do?
  2. What does JSON.stringify() do?
  3. What is JSON used for?

Answers: Converts JSON to an object; converts an object to a JSON string; data exchange between client and server.