JavaScript: JSON (In-Depth)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and easy for machines to parse and generate. JSON is widely used for data exchange between browsers and servers, especially with APIs.

JSON Structure

{
  "name": "Rafi",
  "age": 25,
  "skills": ["JS", "HTML", "CSS"],
  "isActive": true
}
    

Converting JS to JSON

let obj = { a: 1, b: 2 };
let str = JSON.stringify(obj); // '{"a":1,"b":2}'
    

Converting JSON to JS

let s = '{"a":1,"b":2}';
let o = JSON.parse(s); // { a: 1, b: 2 }
    

JSON and APIs

Most web APIs send and receive JSON. Use JSON.stringify() to send, and response.json() or JSON.parse() to receive.

fetch("https://api.example.com/user")
  .then(res => res.json())
  .then(data => console.log(data));
    

Limitations of JSON

let obj = { a: undefined, b: () => {}, c: 123 };
let s = JSON.stringify(obj); // '{"c":123}'
    
Practice: Send, receive, and parse JSON data in your own projects. Try converting JS objects with dates and functions to see what happens!