.json

Term side of the Card.
Topic: Document & Data Formats
Unit title: .json
Categories: Format
Explanation side of the Card

Explanation: The text-based format used for representing structured data, primarily for exchanging data between a server and web applications. It uses key-value pairs and supports data types like strings, numbers, arrays and objects.

Example

Wrongjson
{
  name: 'Ann',
  "age": 31,
}
Rightjson
{
  "name": "Ann",
  "age": 31
}

JSON requires double-quoted keys and strings and does not allow a comma after the last item.

Common mistakes

  • Adding comments or trailing commas to a .json file, which breaks strict parsers.
  • Expecting Date, Map or undefined to survive JSON.stringify() unchanged.
  • Losing precision on large IDs, since JSON numbers become JavaScript doubles.

Key points

  • Keys and strings use double quotes, and there are no trailing commas or comments.
  • JSON.parse() on untrusted input is wrapped in try...catch.
  • Fetch code checks response.ok before calling response.json().
  • Responses send 'application/json' as the Content-Type.

Interview questions

JSON vs YAML: which should I use?

Use JSON for data between programs because it is strict and fast to parse. YAML is easier for people to write by hand in config files.

Can JSON have comments?

No. Standard JSON has no comments. Some tools accept a JSON with comments variant, for example in tsconfig.json.

Why does JSON.stringify turn a Date into a string?

Date has a toJSON() method that returns an ISO string. Parsing gives back a string, so you must convert it to a Date yourself.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy