JSON β A Common Language for Data Exchange
After completing this topic
You will learn what JSON is, why it is used, and how to handle it in JavaScript.
Why JSON?
When a server and a client exchange data, they must agree on a format. Even if the server is Python and the client is JavaScript, they need a format that both can understand.
JSON (JavaScript Object Notation) is that common language. Because it is text-based, it can be read and written in any language. It is practically the standard data format for web APIs.
JSON Structure
{
"name": "Alice",
"age": 25,
"isStudent": false,
"scores": [85, 92, 78],
"address": {
"city": "Seoul",
"zip": "06000"
},
"phone": null
}The rules are simple:
- Keys must be enclosed in double quotes (single quotes are not allowed)
- Values can only be strings, numbers, booleans, arrays, objects, or null
- Functions, undefined, and comments are not allowed
- Trailing commas are not allowed
It is similar to a JavaScript object, but more strict.
JSON.stringify: Object β String
const user = { name: "Alice", age: 25 };
const json = JSON.stringify(user);
console.log(json); // '{"name":"Alice","age":25}'
console.log(typeof json); // "string"This converts a JavaScript object into a JSON string. This is called serialization. It is used when sending data to a server.
To output it nicely:
console.log(JSON.stringify(user, null, 2));The third argument is the number of spaces for indentation.
JSON.parse: String β Object
const json = '{"name":"Alice","age":25}';
const user = JSON.parse(json);
console.log(user.name); // "Alice"
console.log(typeof user); // "object"This converts a JSON string into a JavaScript object. This is called deserialization. It is needed when using data received from the server.
Parsing invalid JSON will result in an error:
JSON.parse("not json"); // SyntaxErrorTherefore, it is safer to use try-catch when parsing API responses.
JSON in API Communication
// Sending data (POST)
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Alice", age: 25 }),
});
// Receiving data (GET)
const res = await fetch("/api/users/1");
const user = await res.json(); // Automatically calls JSON.parsefetch's res.json() automatically calls JSON.parse. When sending data, you must manually convert it using JSON.stringify.
Key Takeaways
JSON is a text-based data exchange format and is practically the standard for web APIs. Use
JSON.stringifyto convert an object to a string andJSON.parseto convert a string to an object. Keys must be enclosed in double quotes; functions and undefined cannot be used.