UTILYARD
Ce guide n'est disponible qu'en anglais.
guides

What is JSON?

A practical introduction to JSON — syntax, data types, common pitfalls, and how to use it in JavaScript.

What is JSON?

JSON stands for JavaScript Object Notation. It was created by Douglas Crockford in the early 2000s as a lightweight, human-readable text format for exchanging data between systems. Despite having "JavaScript" in its name, JSON is entirely language-independent — virtually every modern programming language has built-in support for reading and writing it.

Before JSON became dominant, XML was the standard format for data interchange on the web. XML works, but it's verbose — every value needs an opening and closing tag, namespaces add complexity, and simple structures end up requiring a lot of markup. JSON replaced XML in most modern REST APIs because it's shorter, easier to read at a glance, and maps naturally to the data structures that already exist in most programming languages.

Today JSON is everywhere: API responses, configuration files, log formats, database storage (MongoDB, PostgreSQL's jsonb column type), package manifests like package.json, and editor settings files. It's one of the most important formats to understand as a developer.

JSON syntax

JSON is built on two structures that map to data structures found in almost every programming language:

  • Objects — an unordered collection of key-value pairs, wrapped in curly braces {}. Keys must be strings (in double quotes). Values can be any valid JSON type.
  • Arrays — an ordered list of values, wrapped in square brackets []. Values can be mixed types and can themselves be objects or arrays.

These two structures can be nested inside each other arbitrarily, which is what makes JSON flexible enough to represent almost any data shape. A basic object looks like this:

{
  "name": "Ada Lovelace",
  "age": 36,
  "active": true,
  "tags": ["engineer", "mathematician"],
  "address": {
    "city": "London",
    "country": "UK"
  }
}

Pairs within an object are separated by commas. The last pair must not have a trailing comma — this is one of the most common sources of JSON errors.

JSON data types

JSON supports exactly six value types. Nothing else is valid — no functions, no dates, no undefined, no NaN, no comments.

{
  "stringValue":  "hello, world",
  "integerValue": 42,
  "floatValue":   3.14,
  "boolTrue":     true,
  "boolFalse":    false,
  "emptyValue":   null,
  "objectValue":  { "key": "value" },
  "arrayValue":   [1, 2, 3]
}

String — any sequence of Unicode characters wrapped in double quotes. Escape special characters with a backslash: \n (newline), \" (double quote), \\ (backslash).

Number — integers and floats are the same type. No distinction between int and float. Scientific notation (1.5e3) is valid. Infinity and NaN are not.

Boolean — the literals true or false, always lowercase.

Null — the literal null, representing an intentional absence of value.

Object — a nested key-value map. Objects can be infinitely nested.

Array — an ordered list. Arrays can contain mixed types, including other arrays and objects.

A realistic example

Here's what a typical API response might look like — a user profile returned by a REST endpoint. Notice how objects, arrays, nested objects, and all the primitive types appear together naturally:

{
  "id": 8312,
  "username": "ada.lovelace",
  "email": "ada@example.com",
  "verified": true,
  "avatar": null,
  "plan": "pro",
  "createdAt": "2023-04-12T08:30:00Z",
  "preferences": {
    "theme": "dark",
    "language": "en",
    "notifications": {
      "email": true,
      "push": false
    }
  },
  "roles": ["user", "admin"],
  "lastLogin": "2024-11-01T14:22:10Z"
}

A few things worth noting: dates are stored as strings (ISO 8601 format is the convention, but JSON has no native date type). The avatar field uses null to indicate the user hasn't set one. The preferences object is nested two levels deep to group related settings.

JSON vs XML

XML and JSON can represent the same data — the difference is in verbosity, readability, and ecosystem fit. Here's the same user record in both formats:

<!-- XML -->
<user>
  <id>8312</id>
  <username>ada.lovelace</username>
  <verified>true</verified>
</user>

// JSON
{
  "id": 8312,
  "username": "ada.lovelace",
  "verified": true
}

JSON is shorter, easier to read, and maps directly to objects and arrays in JavaScript (and most other languages). Parsing it is simpler and faster, and there's no need to deal with attributes vs. elements, namespaces, or DTD schemas.

XML still has its place: enterprise systems, SOAP web services, RSS/Atom feeds, SVG, and document-centric formats where mixed content (text with embedded tags) matters. But for the vast majority of modern REST APIs and configuration files, JSON is the right choice.

Common JSON errors

JSON has strict syntax rules. These are the mistakes that show up most often:

Trailing commas

Unlike JavaScript, JSON does not allow a comma after the last item in an object or array. This is the single most common JSON error.

// Invalid — trailing comma
{ "name": "Ada", "age": 36, }

// Valid
{ "name": "Ada", "age": 36 }

Single quotes

JSON requires double quotes for both keys and string values. Single quotes are not valid.

// Invalid — single quotes
{ 'name': 'Ada' }

// Valid
{ "name": "Ada" }

Unquoted keys

In JavaScript you can write { name: "Ada" } without quoting the key. In JSON, that's invalid — every key must be a double-quoted string.

// Invalid — unquoted key
{ name: "Ada" }

// Valid
{ "name": "Ada" }

Comments

JSON does not support comments. Adding // ... or /* ... */ will cause any standard JSON parser to throw an error.

// Invalid — comments not allowed in JSON
{
  // user id
  "id": 8312
}

// Valid
{
  "id": 8312
}

Working with JSON in JavaScript

JavaScript has two built-in methods for working with JSON — both available globally in any browser or Node.js environment.

JSON.parse() — string to object

Use JSON.parse() when you receive a JSON string (from an API response, a file, or localStorage) and need to work with it as a JavaScript object. It throws a SyntaxError if the input is not valid JSON, so wrapping it in a try/catch is good practice.

const jsonString = '{"name":"Ada","age":36}'

try {
  const user = JSON.parse(jsonString)
  console.log(user.name)  // "Ada"
  console.log(user.age)   // 36
} catch (err) {
  console.error('Invalid JSON:', err.message)
}

JSON.stringify() — object to string

Use JSON.stringify() when you need to send data to an API, save it to localStorage, or write it to a file. The optional third argument controls indentation for pretty-printing.

const user = { name: "Ada", age: 36, active: true }

// Compact — for sending over the wire
const compact = JSON.stringify(user)
// '{"name":"Ada","age":36,"active":true}'

// Pretty-printed — for readability or file storage
const pretty = JSON.stringify(user, null, 2)
// {
//   "name": "Ada",
//   "age": 36,
//   "active": true
// }

// Sending in a fetch request
fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(user)
})

Note that JSON.stringify() will silently drop properties with undefined values, functions, and symbols — these types don't exist in JSON.

Try it: JSON Formatter
Paste any JSON to format, validate, and highlight syntax.
Open tool →

Frequently asked questions

Is JSON the same as a JavaScript object?
No. JSON is a text format that looks similar to JavaScript object literals but has stricter rules — keys must be quoted strings, and values can only be the 6 supported types. A JavaScript object can have functions, undefined values, symbol keys, and unquoted keys; none of those are valid in JSON.
Can JSON have comments?
No. Comments are not valid JSON. If you need comments in config files, consider JSON5 or JSONC (used by VS Code and TypeScript's tsconfig), but standard JSON parsers will reject them. A common workaround is adding a "_comment" key, though this pollutes the data.
What's the difference between JSON.parse() and JSON.stringify()?
JSON.parse() converts a JSON string into a JavaScript object you can work with in code. JSON.stringify() does the reverse — it converts a JavaScript object into a JSON string suitable for storage or transmission over a network.
Why do I get 'Unexpected token' errors?
Usually caused by invalid JSON syntax — the most common culprits are trailing commas after the last item in an object or array, single quotes instead of double quotes, unquoted keys, or values like undefined and NaN which aren't valid JSON types. Paste your JSON into a formatter to pinpoint the exact location of the error.
Qu'est-ce que JSON ? — UtilYard