Sub topic 1
What JSON Is and How It Differs from JavaScript Objects
JSON (JavaScript Object Notation) is a text format for exchanging data. Its syntax is borrowed from JavaScript, so a JSON document looks like an object literal. The two are still different things. An object literal is code that the JavaScript engine evaluates. JSON is a string that follows a strict grammar, defined in RFC 8259 and ECMA-404. Many parsing bugs come from treating a JavaScript literal as valid JSON.
Prerequisites
This chapter assumes you already know:
- JavaScript objects, arrays, and primitive types
- Functions and arrow functions
try/catchexception handling- Basic familiarity with HTTP APIs or storing data as text
The JSON data model
JSON has six kinds of value. Anything outside this list cannot appear directly in JSON text.
Objects and arrays nest, so any tree of these values can be represented. JSON has no dates, functions, undefined, symbols, Map, Set, or class instances. When you serialize those, JavaScript has to convert them into one of the six types or drop them. Later chapters cover the exact rules.
Syntax differences that cause errors
An object literal is forgiving. JSON is not. The rules below cause most invalid-JSON errors.
| Feature | JavaScript object literal | JSON text |
|---|---|---|
| Property keys | Unquoted, single, or double quotes | Double quotes required |
| String values | `'single'`, `"double"`, or `` `template` `` | `"double"` only |
| Trailing commas | Allowed | Not allowed |
| Comments | `//` and `/* */` allowed | Not allowed |
| `undefined` | Valid value | Not a JSON value |
| `NaN`, `Infinity` | Valid numbers | Not allowed |
| Numbers | `0x1F`, `.5`, `5.`, `1_000`, `+1` | Decimal only, e.g. `31`, `0.5`, `1000`, `-1`, `1e3` |
| Leading zeros | `007` is an error in strict mode | Not allowed |
| Top-level value | n/a | Any JSON value, e.g. `"hi"`, `42`, `null` |
A JSON document doesn't have to be an object. The strings 42, "hello", and null are each complete, valid JSON texts.
Seeing the difference in code
The snippet below writes the same data as a JavaScript literal and as JSON text. It uses JSON.parse only to check whether each string is valid. The next chapters explain JSON.parse properly.
// JavaScript code: the engine evaluates this into an object.
const literal = {
name: 'Ada', // unquoted key, single-quoted string
skills: ["math", "code",], // trailing comma
// comments are fine here
};
// JSON text: just a string that follows JSON grammar.
const validJson = '{"name":"Ada","skills":["math","code"]}';
const candidates = [
validJson,
"{name: \"Ada\"}", // unquoted key
"{\"name\": 'Ada'}", // single-quoted string
"[1, 2, 3,]", // trailing comma
"{\"n\": NaN}", // NaN is not JSON
"\"just a string\"", // valid: top-level string
"null" // valid: top-level null
];
for (const text of candidates) {
let valid = true;
try {
JSON.parse(text);
} catch {
valid = false;
}
console.log(valid ? "valid " : "invalid", text);
}
console.log(typeof literal); // "object"
console.log(typeof validJson); // "string"Running it prints valid for the first string and the last two, and invalid for the rest. The final two lines show the main point of this chapter. Your code works with objects. JSON is always a string.
Where JSON shows up
You meet JSON as text at the edges of a program. Examples are HTTP request and response bodies, localStorage values, message queues, and files on disk. Inside the program you work with ordinary objects. The two directions are JSON.stringify, which turns a value into text, and JSON.parse, which turns text into a value. The following chapters cover each one in turn.
Exercise
Which of these are valid JSON texts? (1) {'id': 1} (2) {"id": 1, } (3) [true, null, -0.5e2] (4) "ok" (5) {"count": 0x10}
Show answer
Only (3) and (4) are valid. (1) uses single quotes, (2) has a trailing comma, and (5) uses a hexadecimal number. Top-level arrays and strings such as (3) and (4) are allowed.
Exercise
A teammate writes const config = { retries: 3 }; and says the variable "holds JSON." What is wrong with that description?
Show answer
config holds a JavaScript object, not JSON. JSON is text. The object becomes JSON only after something like JSON.stringify(config), which produces the string {"retries":3}.