JavaScript JSON
JSON is a simple text format for storing and sending data. Almost every website and app uses it to talk to servers.
What is JSON?
- JSON stands for JavaScript Object Notation
- It is plain text, so any language can read and write it
- It looks almost the same as a JavaScript object
- APIs (servers that send data) usually reply in JSON
Example
{
"name": "Ayesha",
"age": 21,
"enrolled": true,
"courses": ["HTML", "CSS", "JavaScript"],
"address": { "area": "Orangi Town", "city": "Karachi" }
}JSON Syntax Rules
| Rule | Example |
|---|---|
| Data is in name/value pairs | "city": "Karachi" |
| Names must be in double quotes | "age", not age or 'age' |
| Strings must be in double quotes | "Ali" |
| No trailing comma after the last item | [1, 2, 3] |
| No comments | |
No functions or undefined |
Allowed Values
JSON values can be a string, a number, true or false, null, an array, or an object.
JSON.parse(): Text to Object
When data arrives as JSON text, turn it into a JavaScript object with JSON.parse():
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const text = '{"product":"Ceiling Fan","price":8500,"colours":["white","brown"]}';
const item = JSON.parse(text);
document.getElementById("demo").innerHTML =
item.product + " costs Rs " + item.price + " and comes in " + item.colours.join(" and ");
</script>
</body>
</html>Try it Yourself »Ceiling Fan costs Rs 8500 and comes in white and brown
If the text is not valid JSON, JSON.parse() throws an error. Wrap it in try...catch when the text comes from outside your code.
JSON.stringify(): Object to Text
To send an object to a server or save it, turn it into JSON text with JSON.stringify():
Example
const order = { id: 501, items: ["Chai", "Paratha"], paid: false };
const json = JSON.stringify(order);
console.log(json);
console.log(typeof json);{"id":501,"items":["Chai","Paratha"],"paid":false}
stringAdd two more arguments to make it easy to read: JSON.stringify(order, null, 2) indents with 2 spaces.
Saving Data in localStorage
localStorage keeps data in the browser even after the page is closed, but it only stores strings. JSON solves this.
Example
<!DOCTYPE html>
<html>
<body>
<input id="note" placeholder="Write a note">
<button id="save">Save</button>
<ul id="notes"></ul>
<script>
let notes = [];
try {
notes = JSON.parse(localStorage.getItem("notes")) || [];
} catch (e) {
notes = [];
}
function show() {
document.getElementById("notes").innerHTML = notes.map(n => "<li>" + n + "</li>").join("");
}
document.getElementById("save").addEventListener("click", () => {
const value = document.getElementById("note").value.trim();
if (!value) return;
notes.push(value);
try { localStorage.setItem("notes", JSON.stringify(notes)); } catch (e) {}
show();
});
show();
</script>
</body>
</html>Try it Yourself »Reload the page: if your browser allows storage, your notes are still there.
JSON vs JavaScript Objects
| JavaScript object | JSON |
|---|---|
| Lives in memory while code runs | Is text: can be saved or sent |
| Keys can be written without quotes | Keys must have double quotes |
| Can contain functions | Cannot contain functions |
When you use fetch, await response.json() calls JSON.parse() for you on the response body.
Exercise
Exercise
Which of these is valid JSON?
