JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight data format for storing and transporting data. It's easy for humans to read and write, and easy for machines to parse and generate.

Key Topics

JSON Format

JSON is text-based, using key-value pairs and arrays. Keys and strings must be in double quotes.

JSON.parse() and JSON.stringify()

Use JSON.parse() to convert a JSON string into a JavaScript object, and JSON.stringify() to convert an object to a JSON string.

let obj = { name: "Bob", age: 25 };
let jsonString = JSON.stringify(obj);
console.log(jsonString);
let parsed = JSON.parse(jsonString);
console.log(parsed);

Output

> "{\"name\":\"Bob\",\"age\":25}"

> { name: "Bob", age: 25 }

Explanation: The object is converted to a JSON string and then parsed back into an object.

Fetching Data as JSON

Use fetch() and .json() methods to retrieve JSON data from APIs and servers.

JavaScript Usage in DOM

JSON is commonly used to transfer data between server and client. Parse received JSON and populate the DOM with the resulting data structure.

<script>
fetch('data.json')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // Update DOM with data
    });
</script>

Key Takeaways

  • Format: JSON is a text format with strict syntax.
  • parse/stringify: Convert between objects and JSON strings.
  • Data Transfer: Often used for APIs and AJAX requests.
  • DOM Integration: Parse JSON and render data-driven UIs.