Why this matters
You meet JSON whenever two programs need to share data. A web server sends a list of users as JSON, a configuration file stores settings as JSON, and a mobile app reads its startup data from JSON. It is popular because both humans and machines can read it, and almost every language has a parser for it.
Its main job is transport and storage. When you fill in a form on a website, the browser often packages your input as JSON and sends it to a server. The server replies with JSON that the browser turns back into JavaScript objects. This round trip is the backbone of modern web APIs.
JSON also shows up in configuration for tools and editors, in saved game data, and in logs. Because the format is simple and text-based, you can open a JSON file in any editor and understand what is inside without special software.
The big picture
The key idea is that JSON describes data only. It has values such as strings, numbers, booleans, null, arrays, and objects made of key-value pairs. There are no variables, no loops, and no functions. A JSON document is a snapshot of information, like a photograph, not a set of instructions.
Because JSON is just text, it cannot do anything by itself. To use it, a programming language must parse the text into values it understands, and later serialize those values back into text. The functions that do this live in the host language, not in JSON. This distinction is the most important thing to understand about JSON.
Core ideas
What JSON looks like
A JSON document is text built from a few simple pieces. An object is a set of name-and-value pairs wrapped in curly braces, and an array is an ordered list wrapped in square brackets. Each name is a string in double quotes, and a colon separates the name from its value.
Because JSON is plain text, you can store it in a .json file or send it over a network. Despite the name, it is derived from JavaScript object syntax, but it is a separate standard with its own strict rules. Any language can read it, not just JavaScript.
{
"name": "Ada",
"age": 36,
"skills": ["Python", "JS"]
}
Watch out. Do not confuse JSON with a JavaScript object literal. JSON requires double quotes around every name and forbids comments and trailing commas. A JS object can use single quotes and functions, but JSON cannot.
The six value types
JSON supports exactly six kinds of values. Strings are text in double quotes. Numbers can be whole or decimal and may use exponents. Booleans are the words true and false, all lowercase. Null represents an empty or missing value and is written as the word null.
The last two types are containers: objects, which map string names to values, and arrays, which hold ordered lists of values. That is the whole list. There is no date type, no undefined, no function, and no class. Dates are usually stored as strings, and anything more complex must be represented with these six building blocks.
{
"active": true,
"score": 9.5,
"nickname": null,
"tags": ["a", "b"]
}
Watch out. Do not write NaN, Infinity, or undefined in JSON. They are not valid values. Store missing data as null and convert special numbers to strings if you truly need them.
Objects and arrays
Objects let you label data. Each pair has a key and a value, separated by a colon, and pairs are separated by commas. You look up a value by its key, so order does not matter. Use an object when the meaning of a value comes from its name, such as a person's email address.
Arrays keep things in order. You access items by position, starting at zero, and you use them for collections such as a list of scores or messages. Objects and arrays nest freely, so you can build rich structures like a list of objects, each containing more arrays.
{
"users": [
{ "id": 1, "name": "Ada" },
{ "id": 2, "name": "Bob" }
]
}
Watch out. Duplicate keys in one object are a bad idea. The last one wins in most parsers, and different tools may behave differently. Design your data so each key appears once.
Strict syntax rules
JSON is fussy on purpose, which makes it easy to parse. Names and string values must use double quotes, never single. You cannot add comments, even though many config formats allow them. There is no trailing comma after the last item in an object or array.
Numbers cannot start with a leading zero, and there is no hexadecimal form. Whitespace such as spaces and newlines is allowed anywhere between tokens and is ignored by parsers. Because the rules are strict, a single misplaced comma makes the whole document invalid.
{
"ok": true,
"items": [1, 2, 3]
}
Watch out. A common mistake is pasting a JavaScript object into a .json file. If it contains single quotes, comments, functions, or trailing commas, a strict JSON parser will reject it.
Parsing with JSON.parse
Parsing means converting JSON text into values your language understands. In JavaScript you call JSON.parse with a string and get back the corresponding object or array. This is the moment the data becomes usable: you can now read properties and loop over arrays.
Parsing is strict and fails loudly. If the text is malformed, JSON.parse throws a SyntaxError. That is useful because it tells you about broken data early. In production code you usually wrap parsing in try and catch so one bad response does not crash your whole program.
const text = '{"name": "Ada", "age": 36}';
const user = JSON.parse(text);
console.log(user.name);
Watch out. Do not call JSON.parse on an object. It expects a string. If you already have an object, you are done. If you have a response from fetch, call the response.json method instead.
Serializing with JSON.stringify
Serializing is the reverse of parsing: it turns values in your language into JSON text. JavaScript provides JSON.stringify, which takes an object or array and returns a string you can save or send. This is how you prepare a request body before posting it to an API.
You can pass a replacer argument to control which properties appear, and a space argument to pretty-print the output with indentation. Pretty printing is handy for debugging and for config files people will edit, but it adds extra bytes, so APIs usually send compact JSON.
const user = { name: 'Ada', age: 36 };
const text = JSON.stringify(user, null, 2);
console.log(text);
Watch out. JSON.stringify drops functions, undefined values, and symbol keys. If your object contains a Date, it becomes a string. Plan your data shape with these conversions in mind.
Validating JSON
Valid JSON must follow the grammar of the format, and a parser checks that for you. But valid JSON is not the same as the shape you expect. A document can be perfectly formed and still be missing a field you need, so you must validate the structure too.
In JavaScript you can write simple checks for required properties and their types. In larger projects, libraries such as Zod or Ajv let you describe the expected shape once and validate any input against it. This catches bad data before it reaches the parts of your program that trust it.
const data = JSON.parse(text);
if (!data.name || typeof data.age !== 'number') {
throw new Error('Bad user data');
}
Watch out. Do not assume a parsed value has the fields you want. Check optional fields and array contents. A single missing property deep in the structure can otherwise cause confusing failures later.
JSON in configuration
Many tools store settings in a package.json, a tsconfig.json, or a similar file. The exact rules mean an editor can check the file as you type and flag mistakes immediately. This is one reason JSON won over more relaxed formats for configuration.
When you read a config file in your own program, parse it once at startup and keep the resulting object in memory. Validate the values you depend on, such as port numbers or file paths, and give clear error messages when something is wrong. Config should fail fast and loudly.
Watch out. Do not store secrets such as passwords in a JSON config file that you commit to a repository. Keep them in environment variables or a secret manager.
Data without behaviour
This section is called Data without behaviour because that is the honest truth about JSON. It has no functions, no methods, no loops, and no way to express an action. What you can do is describe values and the relationships between them, then let a real programming language do the work.
So instead of functions inside JSON, you study the functions that surround it: the ones that parse, serialize, validate, and transform. Below you will see how they work in JavaScript and what equivalent tools look like in other languages. You will also see the one rule you must never break.
Why JSON has no functions
JSON was designed to move data between programs, and data must mean the same thing everywhere. A function would carry behaviour that depends on a language, a runtime, and a security context. Leaving behaviour out is what makes a JSON document portable across browsers, servers, phones, and databases.
This is a feature, not a limitation. When you write JSON you are answering what the data is, not what to do with it. The program that reads the document decides the actions. Keeping those two concerns apart makes both easier to reason about.
JSON.parse in JavaScript
JSON.parse takes one argument, a string containing JSON text, and returns the JavaScript value it describes. Objects become plain objects and arrays become arrays. The parser is strict and throws a SyntaxError on anything that is not valid JSON.
Because parsing throws, wrap it in try and catch when the text might be broken, such as data received over a network. Once parsed, the data is an ordinary value you can inspect and transform with normal JavaScript functions.
const text = '{"active": true}';
try {
const data = JSON.parse(text);
console.log(data.active);
} catch (err) {
console.error('Bad JSON');
}
JSON.stringify in JavaScript
JSON.stringify takes a JavaScript value and returns a JSON string. It walks the value and writes each part using the strict rules of the format. Objects become brace-delimited pairs, arrays keep their order, and unsupported values are dropped or changed.
The optional third argument controls indentation. Passing a number adds that many spaces per level, which makes the output pleasant for humans to read. For network requests, leave it out so the payload stays small.
const payload = { name: 'Ada', tags: ['admin'] };
const text = JSON.stringify(payload);
console.log(text);
Equivalents in other languages
Every major language has the same pair of operations under different names. Python calls them loads and dumps in its json module. Java uses libraries such as Jackson, and C# uses System.Text.Json. The idea is always parse text into values and serialize values back into text.
Once you understand one pair, the others are easy to pick up. Watch for differences in how each language maps JSON types to its own types, such as whether numbers become integers or floating point values, and how it handles dates.
import json
data = json.loads('{"name": "Ada"}')
text = json.dumps(data)
Validating the shape
A parser only tells you whether the text is valid JSON, not whether it matches what your program needs. That second check is validation. You look for required keys, confirm types, and decide what to do when a value is missing or unexpected.
For small cases, a few if statements are enough. For larger systems, a schema library lets you describe the expected structure in one place and check every input against it. Good validation gives clear errors near the source of the problem instead of strange failures much later.
const data = JSON.parse(text);
if (!Array.isArray(data.users)) {
throw new Error('users must be an array');
}
Never use eval on JSON
Before JSON.parse existed, some programmers used eval to turn text into objects because eval runs JavaScript code. That is dangerous: JSON text can come from an untrusted source, and eval will execute whatever it contains, not merely read it. A crafted string could run arbitrary code.
JSON.parse was created precisely to avoid this. It accepts only data, never statements or function calls, so it cannot execute behaviour. The rule is simple and absolute: use a real JSON parser, and never eval JSON text, even when you think you control the source.
const data = JSON.parse(text);
// never do this: eval('(' + text + ')');
console.log(data.name);
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
JSON.parse
Parse/serialize function
JSON is only a data format, so it has no functions of its own. JSON.parse is the JavaScript function that turns JSON text into a real value you can read and use.
| Syntax | JSON.parse(text, reviver) |
|---|---|
| Parameters | text — The JSON string to convert reviver — Optional function that transforms each parsed value |
| Returns | The object, array, or primitive described by the text. |
const text = '{"name":"Ada","active":true}';
const data = JSON.parse(text);
console.log(data.name);
What you can do with it. Turn a stored JSON string into an object Read data received as text Rebuild settings saved to disk or storage
Choose it when. Choose JSON.parse when your JSON is still a string rather than an existing object.
| Mistake | Fix |
|---|---|
| Thinking JSON itself has functions | Remember JSON is a format; parsing is done by the host language |
| Passing an already-parsed object | Only pass strings; parsing twice throws an error |
JSON.parse reviver
Parse/serialize option
The reviver argument to JSON.parse lets you inspect and change each value as it is parsed. You use it to convert dates or drop properties in a single pass over the data.
| Syntax | JSON.parse(text, (key, value) => transformed) |
|---|---|
| Parameters | key — The property name for the current value value — The parsed value you may replace or drop |
| Returns | The value to keep for each key; returning undefined deletes the property. |
const text = '{"date":"2026-01-01","secret":"hide"}';
const data = JSON.parse(text, (key, value) => {
if (key === "secret") return undefined;
if (key === "date") return new Date(value);
return value;
});
console.log(data.date.getFullYear());
What you can do with it. Convert ISO date strings into Date objects Strip sensitive fields while parsing Normalize numeric values in one pass
Choose it when. Choose a reviver when you need to transform values during parsing rather than looping afterward.
| Mistake | Fix |
|---|---|
| Returning undefined for values you want to keep | Return the original value unless you intend to delete the property |
| Expecting the reviver to rename keys directly | Return transformed values; build a new object if you must rename keys |
JSON.stringify
Parse/serialize function
JSON.stringify converts a JavaScript value into JSON text. You use it to store data or send it somewhere that expects a plain string rather than a live object.
| Syntax | JSON.stringify(value, replacer, space) |
|---|---|
| Parameters | value — The object or array to convert replacer — Optional function or array selecting properties space — Indentation for readable output |
| Returns | A JSON string, or undefined for values that cannot be serialized. |
const user = {name: "Ada", age: 36};
const text = JSON.stringify(user);
console.log(text);
console.log(JSON.stringify(user, null, 2));
What you can do with it. Save an object to local storage Prepare a request body Produce readable debug output
Choose it when. Choose JSON.stringify when you need text for storage or transfer rather than a live object.
| Mistake | Fix |
|---|---|
| Expecting functions or undefined to be saved | JSON ignores them; convert or remove such values first |
| Stringifying an object with circular references | Remove the circular link or supply a replacer that replaces it |
JSON.stringify replacer
Parse/serialize option
The replacer argument to JSON.stringify controls which properties are written and how values appear. You use it to omit fields or transform values during serialization.
| Syntax | JSON.stringify(value, (key, value) => transformed, space) |
|---|---|
| Parameters | key — The property name for the current value value — The value about to be serialized |
| Returns | The value to write; returning undefined omits the property. |
const user = {name: "Ada", password: "secret", age: 36};
const safe = JSON.stringify(user, (key, value) => {
if (key === "password") return undefined;
return value;
});
console.log(safe);
What you can do with it. Exclude passwords or private fields Keep only an allowlist of keys Convert values to a simpler form for storage
Choose it when. Choose a replacer when you need filtering during serialization rather than cleaning the object first.
| Mistake | Fix |
|---|---|
| Using a function when an array of keys is simpler | Pass an array of allowed key names for plain filtering |
| Expecting the replacer to add new properties | It can only change or drop values, not create new keys |
fetch().json()
Browser method
In the browser, fetch().json() reads a response body as JSON. You use it after a network request to turn the returned text into a usable value your code can work with.
| Syntax | fetch(url).then(response => response.json()) |
|---|---|
| Parameters | url — The address to request response — The fetched response whose body is parsed |
| Returns | A promise resolving to the parsed JSON value. |
fetch("/api/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
What you can do with it. Load data from an API into a page Populate a list from a JSON endpoint Read configuration served as JSON
Choose it when. Choose fetch().json() in browser code when you have a response to parse rather than a plain JSON string.
| Mistake | Fix |
|---|---|
| Forgetting that json() returns a promise | Chain another then or use await to get the actual value |
| Calling json() twice on the same response | Read the body once and reuse the parsed value |
JSON Schema validation
Validation concept
JSON Schema is a separate standard that describes the expected shape of JSON data. You use a validator library to check that a parsed value has the fields and types you require.
| Syntax | validate(instance, schema) |
|---|---|
| Parameters | instance — The parsed JSON value to check schema — An object describing required fields and types |
| Returns | A result that reports whether the data matches and why it fails. |
const schema = {
type: "object",
required: ["name"],
properties: { name: { type: "string" } }
};
const data = JSON.parse('{"name":"Ada"}');
console.log(data.name, schema.required[0]);
What you can do with it. Check API input before processing it Document the shape of a config file Catch missing or wrongly typed fields early
Choose it when. Choose JSON Schema when you must verify the structure of untrusted data rather than trusting parse success.
| Mistake | Fix |
|---|---|
| Assuming JSON validates itself | JSON has no built-in validation; use a schema validator |
| Confusing the schema with the data | The schema describes rules; the instance is the value being checked |
try/catch around parse
Error-handling form
Because JSON.parse throws on malformed text, you wrap it in try/catch. You use this to handle bad input gracefully instead of letting an error stop your whole program.
| Syntax | try { JSON.parse(text); } catch (error) { ... } |
|---|---|
| Parameters | text — The JSON string that may be invalid error — The exception object describing the parse failure |
| Returns | Nothing from the structure; it lets your code continue after a failure. |
let data;
try {
data = JSON.parse("{bad json}");
} catch (error) {
console.error("Invalid JSON:", error.message);
data = {};
}
console.log(data);
What you can do with it. Handle corrupt saved settings Reject invalid user input safely Provide a default when parsing fails
Choose it when. Choose try/catch when input may be malformed rather than assuming every string is valid JSON.
| Mistake | Fix |
|---|---|
| Leaving the catch block empty | Handle or log the error so problems stay visible |
| Using data before confirming parse succeeded | Assign a safe fallback inside catch before continuing |
Array.isArray after parse
Type-check function
After parsing, you may not know whether the result is an array. Array.isArray checks this so you can loop over the data safely instead of guessing.
| Syntax | Array.isArray(JSON.parse(text)) |
|---|---|
| Parameters | value — The parsed value to test |
| Returns | true if the parsed value is an array, otherwise false. |
const data = JSON.parse('[1,2,3]');
if (Array.isArray(data)) {
data.forEach(n => console.log(n));
} else {
console.log("expected a list");
}
What you can do with it. Guard loops over parsed data Distinguish a list from a single object Validate a JSON array response
Choose it when. Choose Array.isArray when the parsed value might not be a list rather than iterating blindly.
| Mistake | Fix |
|---|---|
| Using typeof to detect an array | typeof gives object for arrays; use Array.isArray |
| Assuming all parsed JSON is a list | Check the type before calling array methods |
Object.keys after parse
Object function
Object.keys lists the property names of a parsed object. You use it to inspect or loop over the fields you received when you do not know them in advance.
| Syntax | Object.keys(JSON.parse(text)) |
|---|---|
| Parameters | value — The parsed object whose keys you want |
| Returns | An array of the object's own property names. |
const data = JSON.parse('{"name":"Ada","age":36}');
const keys = Object.keys(data);
console.log(keys);
keys.forEach(key => console.log(key, data[key]));
What you can do with it. List available fields in a response Loop over unknown properties Check whether an expected key is present
Choose it when. Choose Object.keys when you need field names of a parsed object rather than its values.
| Mistake | Fix |
|---|---|
| Calling Object.keys on an array by mistake | Check the type first so you inspect the object you intended |
| Expecting inherited properties to appear | Object.keys returns only own properties |
typeof check
Type-check operator
typeof reports the primitive type of a value. You use it after parsing to check whether you got a string, number, or boolean before you rely on it.
| Syntax | typeof value |
|---|---|
| Parameters | value — The parsed value whose type you want |
| Returns | A string such as "string", "number", "boolean", "object", or "undefined". |
const data = JSON.parse('{"age":36,"name":"Ada"}');
console.log(typeof data.age);
console.log(typeof data.name);
if (typeof data.age === "number") {
console.log("age is numeric");
}
What you can do with it. Verify a field has the expected type Branch on primitive versus object Guard calculations against wrong types
Choose it when. Choose typeof for a quick primitive type check rather than a full schema validation.
| Mistake | Fix |
|---|---|
| Using typeof to detect null or arrays | typeof null and arrays both give object; check separately |
| Comparing typeof result without quotes | Compare against strings like "number" |
structuredClone
Clone function
structuredClone makes a deep copy of a value using the structured clone algorithm. You use it to duplicate parsed data without sharing nested objects with the original.
| Syntax | structuredClone(value) |
|---|---|
| Parameters | value — The value to deep-copy, such as parsed JSON data |
| Returns | A new value with copied nested structures. |
const data = JSON.parse('{"tags":["a","b"]}');
const copy = structuredClone(data);
copy.tags.push("c");
console.log(data.tags);
console.log(copy.tags);
What you can do with it. Copy parsed data before editing it Avoid mutating shared state Snapshot an object for undo behavior
Choose it when. Choose structuredClone when you need a deep copy rather than a shallow reference copy.
| Mistake | Fix |
|---|---|
| Using JSON.parse(JSON.stringify(x)) for copying | structuredClone is clearer and handles more types |
| Expecting functions or DOM nodes to clone | structuredClone cannot copy those; it throws for unsupported types |
localStorage getItem parse
Browser storage pattern
Values stored in localStorage are always strings, so you parse them after reading. You use this pattern to recover objects you saved earlier in the same browser.
| Syntax | JSON.parse(localStorage.getItem(key)) |
|---|---|
| Parameters | key — The localStorage key to read fallback — A default used when nothing is stored |
| Returns | The parsed value, or the fallback when the key is missing. |
const raw = localStorage.getItem("settings");
const settings = raw ? JSON.parse(raw) : { theme: "light" };
console.log(settings.theme);
localStorage.setItem("settings", JSON.stringify(settings));
What you can do with it. Restore user preferences on page load Read saved app state Rebuild a cart from storage
Choose it when. Choose this pattern when reading stored JSON rather than treating the raw string as an object.
| Mistake | Fix |
|---|---|
| Parsing a missing key directly | Check for null first or provide a fallback, since getItem can return null |
| Storing an object without stringifying | Save with JSON.stringify so it can be parsed back |
Common mistakes here
| Mistake | Fix |
|---|---|
| Assuming JSON can contain functions or methods. | Describe only data. Put behaviour in the program that reads the JSON. |
| Using eval to parse JSON text. | Use JSON.parse, which is safer and accepts only valid JSON data. |
| Expecting comments or trailing commas to be accepted. | Remove them, because strict JSON forbids both. |
| Skipping validation of parsed data. | Check required fields and types before trusting the values. |
| Stringifying an object with functions and expecting them to survive. | Functions and undefined are dropped, so redesign the data as plain values. |
The example, line by line
This JavaScript program parses a JSON string, filters the users it contains, and writes a small report back out as JSON.
| Code | What it does |
|---|---|
1const raw = '{"users":[{"name":"Ada","age":36},{"name":"Bob","age":28},{"name":"Cleo","age":41}]}'; | Store a string of JSON text, the format in which data often arrives. |
2const data = JSON.parse(raw); | Parse the text into a JavaScript object so its values become usable. |
3if (!Array.isArray(data.users)) { | Check that the parsed object really contains a users array, since parsing alone cannot guarantee it. |
4 throw new Error('Expected a users array'); | Stop with a clear error if the shape is wrong. |
5} | Close the validation block. |
6const adults = data.users.filter(user => user.age >= 30); | Keep only users whose age is thirty or older using a filter callback. |
7const names = adults.map(user => user.name); | Turn the remaining user objects into an array of just their names. |
8const report = { count: names.length, names: names }; | Build the report object with a count and the list of names. |
9const text = JSON.stringify(report, null, 2); | Serialize the report back into JSON text with two-space indentation. |
10console.log(text); | Print the finished JSON text. |
const raw = '{"users":[{"name":"Ada","age":36},{"name":"Bob","age":28},{"name":"Cleo","age":41}]}';
const data = JSON.parse(raw);
if (!Array.isArray(data.users)) {
throw new Error('Expected a users array');
}
const adults = data.users.filter(user => user.age >= 30);
const names = adults.map(user => user.name);
const report = { count: names.length, names: names };
const text = JSON.stringify(report, null, 2);
console.log(text);
Worked variations
JSON in Python
Python's standard library handles JSON through the json module. The loads function parses text into dictionaries and lists, while dumps turns those values back into a string. The names stand for load string and dump string.
The mapping is close to JavaScript: JSON objects become dictionaries and JSON arrays become lists. This makes Python a common choice for reading API responses in scripts and data pipelines.
import json
with open('users.json') as f:
users = json.load(f)
print(users[0]['name'])
A config file example
Configuration is one of the most common places you will see JSON. This small file sets a port, a debug flag, and a list of allowed origins. An editor can check the syntax as you type because the rules are strict.
When your program loads it, validate the types you rely on. A missing port or a string where a number belongs should produce a clear error at startup.
{
"port": 3000,
"debug": false,
"origins": ["https://example.com"]
}
Common mistakes
| Mistake | Fix |
|---|---|
| Writing single quotes around names and string values in JSON. | Use double quotes everywhere in JSON text. |
| Leaving a trailing comma after the last property or array item. | Remove it, because strict JSON parsers reject trailing commas. |
| Trying to store a Date object or a function directly in JSON. | Convert dates to strings and represent behaviour outside the data. |
| Trusting parsed data without checking its shape. | Validate required fields and types before using the values. |
| Hand-writing JSON by string concatenation instead of using a serializer. | Use JSON.stringify or the equivalent so values are escaped correctly. |
Practice
- Write a JSON object that describes a book with a title, an author, a year, and a list of tags.
- Use JSON.parse on a string you write yourself, then print one of its properties.
- Take an object in JavaScript, serialize it with JSON.stringify, and confirm the text is valid by parsing it again.
- Write a validator that checks a parsed object has a name string and an age number, throwing a clear error otherwise.