Sub topic 1
What JSON Is and How It Differs from JavaScript Objects
Prerequisites
This chapter assumes you know JavaScript objects, arrays, and primitive types, and that you can write arrow functions and try/catch blocks. Some experience sending or storing data as text, for example through an HTTP API, will help.
JSON Versus Object Literals
JSON (JavaScript Object Notation) is a text format for data. It looks like JavaScript, but its rules are stricter.
| Feature | JavaScript literal | JSON |
|---|---|---|
| Property keys | Quoted or unquoted | Double-quoted only |
| Strings | `'single'` or `"double"` | `"double"` only |
| Trailing commas | Allowed | Not allowed |
| Comments | Allowed | Not allowed |
| Values | Any value | string, number, boolean, null, object, array |
{ name: 'Ada', } is a valid JavaScript object literal. As JSON it is invalid. The valid JSON version is {"name":"Ada"}.
Turning Values into Text with JSON.stringify
JSON.stringify turns a value into a compact JSON string. JSON.parse does the reverse. A parsed result is always a new object, unconnected to the original.
const user = { name: "Ada", age: 36, tags: ["math", "code"] };
const text = JSON.stringify(user);
console.log(text); // {"name":"Ada","age":36,"tags":["math","code"]}
const copy = JSON.parse(text);
console.log(copy.tags[1]); // "code"
console.log(copy === user); // falseReading JSON Text with JSON.parse
JSON.parse takes a string and builds the matching objects, arrays, and primitives. If the input breaks any JSON rule, such as single quotes or a trailing comma, it throws a SyntaxError. The next chapter shows how to handle that error.
Values JSON Cannot Represent
Some JavaScript values have no JSON form, and stringify handles each one differently. This is where many bugs start.
const data = {
a: undefined,
b: () => 1,
c: Symbol("s"),
d: NaN,
e: new Date(0)
};
console.log(JSON.stringify(data));
// {"d":null,"e":"1970-01-01T00:00:00.000Z"}
console.log(JSON.stringify([undefined, () => 1, Symbol("s")]));
// [null,null,null]
console.log(JSON.stringify(undefined)); // undefined (not a string)- When
undefined, a function, or a symbol is an object property, the property is dropped. - In an array, those same values become
null, so the array keeps its indexes. NaNandInfinitybecomenull.- A Date becomes an ISO string through its built-in
toJSON. Parsing that string later gives you a string back, not a Date.
Exercise
What does JSON.stringify({ x: [NaN, undefined], y: undefined, z: 0 }) return?
Show answer
'{"x":[null,null],"z":0}'. In the array, NaN and undefined both become null. The property y is dropped because its value is undefined.