JSON and Data Exchange
JSON stands for JavaScript Object Notation. It is a text format for storing and sending data, and it looks almost exactly like a JavaScript object. Every modern web app uses it, because it is the common language browsers and servers speak when they exchange information.
JSON keeps data in key-value pairs wrapped in curly braces, and it supports the same basic types as JavaScript: strings, numbers, booleans, arrays, null, and nested objects. One important difference: every key and every string in JSON must use double quotes, so JSON is stricter than a normal JavaScript object.
The two functions you use are JSON.parse and JSON.stringify. parse reads a JSON string and turns it into a usable JavaScript value. stringify does the reverse, taking an object or array and turning it into a JSON string you can save or send. Web requests, local storage, and API calls all run through these two functions.
JSON.parse turns text into data
When a server sends data, it arrives as a string. JSON.parse converts that string into a real object or array you can work with. If the text is not valid JSON, parse throws an error, which is a common cause of crashes in web code.
const text = '{"name":"Ada","age":36}';
const user = JSON.parse(text);
console.log(user.name); // "Ada"
JSON.stringify turns data into text
Sending data works in reverse: you stringify an object into a JSON string and send it in a request or save it to storage. The optional second argument filters or transforms values, and the third indents the output for readability.
const user = { name: "Ada", age: 36 };
const text = JSON.stringify(user);
console.log(text); // {"name":"Ada","age":36}
JSON in the real world
APIs respond with JSON, forms send JSON to servers, and local storage only saves strings, so JSON.stringify and JSON.parse are the bridge. A typical flow: fetch data as a string, parse it, render it on the page, then stringify the result before storing it.
// Save to local storage, then read it back
localStorage.setItem("user", JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem("user"));
Syntax
const user = { name: "Ada", age: 36, skills: ["math", "writing"] };
const json = JSON.stringify(user); // object to JSON string
const copy = JSON.parse(json); // JSON string back to object
console.log(copy.name); // "Ada"
JSON.parse Throws on Bad JSON
JSON.parse("not json") throws and stops script — wrap in try/catch.
try{ JSON.parse(s)}catch(e){}
Good to know
- JSON is the text format browsers and servers use to exchange data.
- JSON.parse converts a JSON string into a JavaScript value.
- JSON.stringify converts a JavaScript value into a JSON string.
- Keys and strings in JSON must use double quotes.
- Wrap parse in try catch so invalid data shows a message instead of crashing.