JavaScript JSON
JSON is a lightweight, text-based format for storing and exchanging structured data between programs.
What is JSON?
JSON stands for JavaScript Object Notation. It is a plain-text format for representing structured data as a string, and it has become the standard way for web applications and servers to talk to each other. Although the syntax looks almost identical to JavaScript object literals, JSON is language-independent: Python, Java, Go, and nearly every other language can read and write it.
Because JSON is just text, it can be saved to a file, stored in a database, or sent across a network. When your JavaScript program receives JSON, it converts that text into real objects and arrays it can work with; when it needs to send data out, it converts its objects back into a JSON string.
JSON syntax rules
- Data is written as name/value pairs, for example "name": "Ada".
- Property names (keys) must be wrapped in double quotes, never single quotes.
- Values may be a string, number, boolean, null, an object, or an array.
- Objects are enclosed in curly braces {} and arrays in square brackets [].
- No trailing commas, no comments, and functions or undefined are not allowed.
Converting between JSON and objects
JavaScript provides a built-in JSON object with two key methods. JSON.parse() turns a JSON string into a JavaScript value, and JSON.stringify() turns a JavaScript value into a JSON string. These two methods are the bridge between text and live data.
Parsing a JSON string into an object
<!DOCTYPE html>
<html>
<body>
<h2>Parsing JSON</h2>
<script>
const text = '{"name": "Ada", "age": 36, "active": true}';
const user = JSON.parse(text);
console.log(user.name); // "Ada"
console.log(user.age); // 36
console.log(typeof user); // "object"
</script>
</body>
</html>Turning an object into a JSON string
<!DOCTYPE html>
<html>
<body>
<h2>Creating JSON</h2>
<script>
const project = {
title: "Learn JS",
tags: ["json", "web"],
published: false
};
// Second and third arguments add pretty-printing
const json = JSON.stringify(project, null, 2);
console.log(json);
// {
// "title": "Learn JS",
// "tags": [ "json", "web" ],
// "published": false
// }
</script>
</body>
</html>Working with nested data
<!DOCTYPE html>
<html>
<body>
<h2>Nested JSON Data</h2>
<script>
const response = '{"users":[{"id":1,"name":"Sam"},{"id":2,"name":"Lee"}]}';
const data = JSON.parse(response);
data.users.forEach((u) => {
console.log(u.id + ": " + u.name);
});
// 1: Sam
// 2: Lee
</script>
</body>
</html>Exercise: JavaScript JSON
What happens to a function property on an object when you run JSON.stringify() on it?