Introduction to JSON
JSON, short for JavaScript Object Notation, is a plain text format for structured data. It is the standard way web APIs send data between a server and a browser: a React app requests a list of products and receives JSON, and when it submits a form it often sends JSON back. Although the syntax comes from JavaScript object literals, JSON is language independent, and Python, Java, PHP and almost every other language can read and write it.
The building blocks
JSON allows exactly six kinds of value:
- Objects: unordered sets of key/value pairs inside curly braces.
- Arrays: ordered lists inside square brackets.
- Strings: text in double quotes.
- Numbers: integers or decimals, with no leading zeros, and no
NaNorInfinity. - Booleans:
trueorfalse. - null: an intentional empty value.
{
"id": 1024,
"name": "Riya Sharma",
"isMember": true,
"skills": ["HTML", "CSS", "JavaScript"],
"address": {
"city": "Pune",
"pin": "411001"
},
"manager": null
}
Stricter than a JavaScript object
JSON looks like a JavaScript object, but its rules are tighter. Keys must be in double quotes. Strings must use double quotes, never single quotes. Trailing commas after the last item are not allowed. Comments are not allowed. Functions, undefined and dates have no JSON form; dates are usually sent as ISO 8601 strings (year, month and day, then the time), which is exactly what Date.prototype.toISOString() produces.
Converting in JavaScript
The built-in JSON object has two methods. JSON.stringify(value) turns a JavaScript value into a JSON string, which you need before sending data in a request body or saving it to localStorage. JSON.parse(text) does the opposite, turning a JSON string back into objects and arrays.
const user = { name: 'Riya', skills: ['HTML', 'CSS'], greet() {} };
const text = JSON.stringify(user);
// '{"name":"Riya","skills":["HTML","CSS"]}' (the method is dropped)
const pretty = JSON.stringify(user, null, 2); // indented for reading
const copy = JSON.parse(text);
console.log(copy.skills[1]); // "CSS"
try {
JSON.parse("{'name': 'Riya'}"); // single quotes are invalid
} catch (err) {
console.error('Bad JSON:', err.message);
}
With fetch(), calling response.json() reads the body and parses it for you, returning a promise of the resulting value.
JSON.stringify() also accepts a second argument to control what is included. Passing an array of property names, such as JSON.stringify(user, ['name']), keeps only those keys. Objects can define a toJSON() method to decide how they are serialised, which is how Date objects turn themselves into strings.
Errors you will run into
"Unexpected token" errors from JSON.parse usually mean the text is not JSON at all. A common case is a server returning an HTML error page, so response.json() fails on the opening < character. Check the response status and content type before parsing.
Another mistake is forgetting to stringify. Passing an object straight into a fetch body sends the text "[object Object]". Always use JSON.stringify() and set the Content-Type: application/json header.
Also note that JSON.parse(JSON.stringify(obj)) is sometimes used to copy objects, but it silently drops functions and undefined and turns dates into strings. structuredClone() is the better tool for deep copies.
Key points
JSON is text with six value types, double quotes everywhere and no trailing commas. Use stringify to send and parse to receive, and wrap parsing of untrusted input in try/catch.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.