What you need to know about JSON:
- JSON stands for JavaScript Object Notation - a plain-text format for storing and exchanging structured data
- It has six data types: strings, numbers, booleans, null, arrays, and objects
- Syntax rules are strict: keys must be double-quoted strings, trailing commas break it, no comment syntax
- Data is structured using objects (key/value pairs in curly braces) and arrays (ordered lists in square brackets) - both can be nested
- In JavaScript,
JSON.parse()converts a JSON string into an object;JSON.stringify()does the reverse - JSON is the default format for REST APIs, largely because every language and browser handles it natively
- JSON Schema lets you define and validate the expected structure of a document before your application processes it
- JSONP is a legacy cross-origin workaround - mostly replaced by CORS in anything built recently
What Is JSON and Why It Matters
JSON (JavaScript Object Notation) is a lightweight JSON data format for storing and exchanging structured data. It's a plain-text format every major language reads and writes natively - which is the main reason it's used almost everywhere. The JSON advantages it offers are straightforward: no special libraries, no conversion layers, and a structure that maps directly to the objects developers are already working with. Douglas Crockford defined it in the early 2000s, and it's now standardized in RFC 8259 and ECMA-404.
JSON vs XML: Key Differences
A JSON vs XML comparison comes down to verbosity. XML wraps every value in opening and closing tags; JSON uses key/value pairs with minimal punctuation, and the JSON format maps directly to the data structures you're already working with in code.
Here's the same data in both formats:
XML:
<user>
<name>Alice</name>
<age>30</age>
</user>JSON:
{
"name": "Alice",
"age": 30
}XML still makes sense for document markup and enterprise systems with strict schema requirements. For APIs and config files, JSON is what you'll actually encounter.
JSON vs CSV and YAML
In a JSON vs CSV comparison, CSV handles flat tabular data cleanly but falls apart the moment your data has any hierarchy. A JSON vs YAML comparison is closer - YAML supports the same structures as JSON and allows comments, which is genuinely useful for config files, but one misplaced space breaks the whole file. JSON is less flexible than YAML but far more forgiving and universally supported.
| Feature | JSON | CSV | YAML |
|---|---|---|---|
| Human readable | Yes | Yes | Yes |
| Supports data types | Yes | No | Yes |
| Nested data | Yes | No | Yes |
| Comments | No | No | Yes |
| Native browser parsing | Yes | No | No |
Advantages of Using JSON
What is JSON really offering over the alternatives? JSON advantages are mostly practical. The JSON format is universally supported: browsers parse it natively, every language ships with a built-in parser, and both ends of an API call can read it without any translation step in between.
The one genuine limitation: no comment syntax. For config files in version control, that's annoying. For API payloads, nobody misses them.
Understanding JSON Syntax
JSON syntax has two structures: objects (key/value pairs in curly braces) and arrays (ordered lists in square brackets). Everything else is a value sitting inside one of those.
The rules are strict and unforgiving:
- Keys must be strings in double quotes
- No trailing commas - the parser rejects the whole file
- No comments, full stop
- Pairs are separated by commas
- Values must be one of the six supported data types
JSON Key/Value Pairs Explained
A JSON object is a collection of key/value pairs. Here's a JSON example showing typical server config data:
{
"hostname": "server01",
"port": 8080,
"active": true
}The JSON syntax stays the same regardless of what the data represents. A server config and a user profile are structurally identical - just different keys and values.
JSON Data Types Overview
JSON supports exactly six JSON data types. Here's what each one looks like - and where things commonly go wrong. Each JSON example below is intentionally minimal; real-world usage just nests these inside objects and arrays.
String
A JSON string is any sequence of Unicode characters in double quotes. It's the most frequently used of all the JSON data types - and the most common mistake is using single quotes, which aren't valid.
{ "city": "Munich" }Number
JSON doesn't distinguish between integers and floats - both are just numbers as far as the JSON data types spec is concerned. This JSON example covers both:
{ "cores": 8, "price": 6.99 }Boolean
A JSON boolean is true or false. Lowercase, no quotes - those are the only valid options, and they apply consistently across all JSON data types that represent truth values.
{ "enabled": true, "debug": false }Null
Representing absence, JSON null is its own distinct entry among the JSON data types - not a synonym for an empty string or zero.
{ "middleName": null }A field set to null and a field that doesn't exist at all are technically different things. Keep this in mind when writing parsers.
Array
A JSON array is an ordered list of values in square brackets - one of the more versatile JSON data types since it can hold strings, numbers, objects, or other arrays.
{ "ports": [80, 443] }Object
Nesting a JSON object inside another object is how you model anything with real hierarchical structure. It's the most expressive of the JSON data types and the pattern underlying most real-world API responses.
{
"server": {
"hostname": "server01",
"port": 8080
}
}How to Store JSON Data
Choosing between a JSON object and a JSON array comes down to whether your data has named properties or is an ordered collection. Most real JSON format responses use both together.
Using JSON Objects
A JSON object works best for data with named properties - a user record or a single API resource. The JSON syntax is the same throughout, and each JSON example follows the same key/value pattern.
{ "id": 1, "name": "Alice", "active": true }Using JSON Arrays
A JSON array is for ordered collections - anything where you're dealing with multiple instances of the same structure. This JSON example also shows how objects nest naturally inside arrays, which is the pattern you'll see in the vast majority of API responses.
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]Nested Objects and Arrays in JSON
Real-world JSON almost always involves nesting. A JSON object contains a JSON array, that array contains more objects, those objects contain further values. There's no depth limit in the spec, though production APIs can get surprisingly deep before anyone thinks to flatten them. Here's a clean JSON example:
{
"cluster": "eu-west",
"nodes": [
{ "id": "node1", "status": "active" },
{ "id": "node2", "status": "standby" }
]
}Working with JSON in Code
The two functions you'll use constantly are JSON parse and JSON stringify. JSON schema validation comes into play once you're handling external or untrusted data. Together, they cover the vast majority of real JSON example scenarios in JavaScript.
Parsing JSON with JSON.parse
The JSON parse operation takes a JSON string and returns a JavaScript object. It's the standard entry point for handling API responses, and a good JSON tutorial will always tell you to wrap it in error handling.
const data = JSON.parse('{"name":"Alice","age":30}');
console.log(data.name); // "Alice"Pass it invalid JSON and it throws a SyntaxError. Always wrap untrusted input in a try/catch - this is the mistake that shows up most in production logs.
try {
const data = JSON.parse(input);
} catch (e) {
console.error("Invalid JSON:", e.message);
}JSON.stringify() Method
Every JSON tutorial covers JSON stringify alongside JSON parse because you need both when working with APIs. JSON.stringify() goes the other direction - object in, string out.
const str = JSON.stringify({ name: "Alice", age: 30 });
// '{"name":"Alice","age":30}'Pass a third argument for indented output, which is what most people are looking for when they search JSON prettify. The JSON stringify method is probably the most-used JSON function in JavaScript.
JSON.stringify(obj, null, 2);JSON Schema Validation
JSON schema is a vocabulary for describing the expected structure of a JSON document. You define required fields and their allowed JSON data types, then run incoming data through a validator before your application touches it.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name"]
}Catching bad data at the entry point beats debugging it three functions in. For API inputs especially, JSON schema validation is one of the more underused tools in the stack.
JSON in APIs and Web Applications
The default JSON format is best for REST APIs. When you make a JSON API call, the response almost always comes back as a JSON object or array with Content-Type: application/json in the header. And JSONP aside, this is how the web has handled structured data exchange for well over a decade.
How JSONP Works
JSONP (JSON with Padding) is a pre-CORS workaround for cross-origin restrictions. Instead of returning raw JSON API data, the server wraps the response in a function call:
callback({ "name": "Alice" });The browser loads it as a script tag and executes it. You'll mostly see JSONP in older codebases now - knowing what it is saves twenty minutes of confusion when you run into it.
JSON API Format
JSON:API is a formal specification for structuring API responses in JSON format. It standardizes how resources and errors appear in the response body, so any client built for it can consume any compliant JSON API endpoint without custom parsing logic. Worth knowing if you're building a public API or integrating with one at scale.
JSON Cheat Sheet
A quick reference covering JSON syntax, JSON data types, and common JSON example patterns:
| Element | Syntax | Example |
|---|---|---|
| Object | { "key": value } | { "name": "Alice" } |
| Array | [ value, value ] | [ 80, 443 ] |
| String | "text" | "hello" |
| Number | 123 or 1.5 | 8080 |
| Boolean | true / false | true |
| Null | null | null |
| Nested object | { "key": { } } | { "server": { "port": 80 } } |
| Nested array | { "key": [ ] } | { "ports": [80, 443] } |
| Parse (JS) | JSON.parse(str) | JSON.parse('{"a":1}') |
| Stringify (JS) | JSON.stringify(obj) | JSON.stringify({ a: 1 }) |
JSON FAQ
What is JSON good for, practically speaking? Data exchange. Most web applications rely on JSON API responses by default, and the JSON format shows up in config files everywhere from Docker to VS Code. It became the standard because both ends of a request can read it without extra libraries or conversion steps.
JSON schema is a vocabulary for validating document structure. Write a JSON schema that defines required fields and allowed JSON data types, run incoming data through a validator, and catch bad payloads before they reach your application logic.
A JSON array is an ordered list of values in square brackets: [1, 2, 3] or [{"id": 1}, {"id": 2}]. Unlike objects, order is preserved, and a JSON array can hold any of the JSON data types, including other arrays and objects.
The JSON parse pattern is the same across languages - string in, data structure out. In JavaScript: JSON.parse(string). Python: json.loads(). PHP: json_decode(). Every JSON tutorial covers error handling too, because invalid input throws rather than returning null.
In a JSON vs XML comparison, the main gap is verbosity. XML wraps every value in named tags; JSON uses key/value pairs and browsers parse it natively. The JSON format is shorter and maps more directly to the objects you're working with in code. XML still has real advantages in document markup and complex namespace scenarios, but for most API work, JSON is the default.