JSON (JavaScript Object Notation) is a text format for data. It looks almost exactly like JavaScript objects and arrays, which is a big part of why it became the standard way for programs to exchange data on the web. APIs send JSON, apps save settings as JSON, and many configuration files are JSON.
Because JSON is plain text, any programming language can read and write it, not only JavaScript. A server written in Python can send JSON that your JavaScript reads, and the other way round. Learning JSON is the step that lets your pages work with data from the outside world.
What JSON looks like
{
"name": "Pixel",
"age": 2,
"vaccinated": true,
"toys": ["ball", "rope"],
"owner": null
}Data like this can be nested as deeply as you need: objects inside arrays inside objects. Most API responses are larger versions of exactly this structure.
JSON's strict syntax rules
- Keys must be wrapped in double quotes, as in
"name". - Strings use double quotes only.
- Allowed values are strings, numbers,
trueandfalse,null, arrays and objects. - Not allowed: functions,
undefined, comments, trailing commas and single quotes.
These rules are stricter than JavaScript's, which is the most common source of "invalid JSON" errors. A single trailing comma or a single quote is enough to make the whole text unreadable.
Converting between JSON and JavaScript
| Method | Converts |
|---|---|
JSON.stringify(value) | a JavaScript value into a JSON string |
JSON.parse(text) | a JSON string into a JavaScript value |
JSON.stringify(obj, null, 2) adds line breaks and two-space indentation, which makes the output much easier to read while debugging.
JSON.stringify quietly leaves out properties whose values are functions or undefined, because JSON can't represent them.
Parsing JSON safely
JSON.parse throws an error if the text isn't valid JSON. When the text comes from somewhere you don't control, such as a file, browser storage or a server, wrap the call in try...catch (see Errors) and fall back to a sensible default.
JSON Syntax
JSON methods
const text = JSON.stringify({ a: 1 }); // '{"a":1}'
const obj = JSON.parse('{"a":1}'); // { a: 1 }
const pretty = JSON.stringify(obj, null, 2); // indentedJSON Summary
- JSON is a text format for data that looks like JavaScript objects and arrays.
- Keys and strings must use double quotes; comments and trailing commas aren't allowed.
JSON.stringifyturns a value into a JSON string;JSON.parseturns it back.- Functions and
undefinedare dropped byJSON.stringify. - Wrap
JSON.parseintry...catchwhen the text comes from outside your code.
JSON Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Stringify and parse
const order = {
id: 1042,
items: ["Latte", "Muffin"],
paid: true,
note: undefined,
print() { return "hi"; },
};
const json = JSON.stringify(order);
console.log(json);
console.log(typeof json);
const back = JSON.parse(json);
console.log(back.items[1], typeof back);
console.log(JSON.stringify(order, null, 2));Line-by-line explanation
- Lines 1 to 7A normal JavaScript object, including
undefinedand a method. - Line 9Turn it into a JSON string.
noteandprintare dropped because JSON can't store them. - Line 13Turn the string back into an object.
- Line 16Pretty-printed with 2-space indentation.
Reading API-style data
This string is exactly the kind of text a weather API might send.
const response = '{"city":"Oslo","temp":-3,"forecast":[{"day":"Mon","sky":"snow"},{"day":"Tue","sky":"sun"}]}';
const weather = JSON.parse(response);
console.log(`${weather.city}: ${weather.temp}°C`);
weather.forecast.forEach(f => console.log(`${f.day} → ${f.sky}`));Line-by-line explanation
- Line 1Raw JSON text.
- Line 3Parse it into an object we can use.
- Lines 5 to 6Now it's normal JavaScript data.
Handling invalid JSON
const inputs = ['{"ok":true}', "{ok: true}", "{'ok': true}", ""];
for (const text of inputs) {
try {
const data = JSON.parse(text);
console.log("✅ Parsed:", data);
} catch (error) {
console.log("❌ Invalid JSON:", JSON.stringify(text));
}
}Line-by-line explanation
- Line 1One valid JSON string, three invalid ones (unquoted key, single quotes, empty).
- Lines 4 to 9
try…catchstops one bad input from crashing everything.
Common JSON Mistakes
Using single quotes or unquoted keys
{ name: 'Sam' }{ "name": "Sam" }That's valid JavaScript, but not valid JSON.
Parsing something that's already an object
const user = { name: "Sam" };
JSON.parse(user); // SyntaxError: "[object Object]" is not valid JSONconst user = JSON.parse('{"name":"Sam"}');JSON.parse takes a string. If you already have an object, you don't need it.
Trailing commas
{ "a": 1, "b": 2, }{ "a": 1, "b": 2 }JSON in Real Projects
JSON is the web's data language
When a weather app, a social feed or a game leaderboard loads data, it's almost always JSON. package.json describes JavaScript projects, VS Code settings are JSON, and localStorage uses JSON to save objects. Next up: loading JSON from real APIs with fetch.
JSON Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Turn the object into JSON, then back again.
const text = JSON.({ score: 10 });
const data = JSON.(text);
Which is valid JSON?
What does this print?
console.log(JSON.stringify({ a: 1, b: undefined, c: null }));The code should parse the saved settings and log Theme: dark. Fix it.
const saved = "{'theme': 'dark', 'size': 16,}";
const settings = JSON.parse(saved);
console.log("Theme:", settings.theme);- Logs "Theme: dark"
- No errors
JSON Quiz
3 questions to check what you learned.
What does JSON stand for?
- Java Standard Object Notation
- JavaScript Object Notation
- JavaScript Online Network
- JSON Simple Object Name
What type does
JSON.stringify([1, 2])return?- array
- object
- string
- number
Can JSON contain functions?
- Yes
- No
- Only arrow functions
- Only in arrays
JSON Challenge
Safe JSON loader
Write a function safeParse(text, fallback) that:
- Returns the parsed value if
textis valid JSON - Returns
fallbackif parsing fails (usetry…catch)
So safeParse('[1,2]', []) → [1, 2] and safeParse("oops", []) → [].
function safeParse(text, fallback) {
// your code
}
console.log(safeParse('[1,2]', []));
console.log(safeParse("oops", []));- Parses valid JSON
- Returns the fallback for invalid JSON
- Handles an empty string
- Uses try…catch