Introduction to JSON
By Flavio Copes
Learn JSON syntax, supported values, objects and arrays, and how to parse and serialize JSON safely in JavaScript.
JSON is a text format used to store and exchange data.
It can represent an object, an array, a string, a number, a boolean, or null. A complete JSON document does not have to be an object.
JSON is language-independent, even though its syntax came from JavaScript. It is defined by ECMA-404 and RFC 8259.
Here’s an object written as JSON:
{
"name": "Flavio",
"age": 35
}
Property names and string values use double quotes. A colon separates each name from its value, and commas separate members.
JSON allows spaces, tabs, line feeds, and carriage returns around its structural characters. The above is equivalent to:
{"name": "Flavio","age": 35}
or
{"name":
"Flavio","age":
35}
Formatting does not change the data, but indentation makes it easier to read.
(If you need to validate or pretty-print a JSON string, you can use my JSON formatter and validator — it runs entirely in the browser.)
JSON text is commonly stored in .json files and transmitted over the network with an application/json media type.
JSON syntax rules
JSON is stricter than a JavaScript object literal:
- property names and strings must use double quotes
- comments are not allowed
- trailing commas are not allowed
undefined, functions, symbols,NaN, andInfinityare not valid JSON values- object member names should be unique for reliable interchange
For example, this is invalid JSON:
{
"name": "Flavio",
}
Data types
JSON supports some basic data types:
Number: a base-10 number, with optional fraction and exponent partsString: Unicode text wrapped in double quotesBoolean:trueorfalseArray: a list of values, wrapped in square bracketsObject: a set of key-value pairs, wrapped in curly bracketsnull: thenullword, which represents an intentional null value
JSON numbers do not support NaN or infinity. Very large integers can also lose precision when parsed as JavaScript numbers, so APIs often transmit them as strings.
Other data types need an agreed representation. A Date, for example, is commonly stored as a string.
Encoding and decoding JSON in JavaScript
JavaScript provides JSON.parse() and JSON.stringify() through the JSON object.
Use JSON.parse() to turn JSON text into a JavaScript value:
const text = '{"name":"Flavio","age":35}'
const person = JSON.parse(text)
person.name //'Flavio'
Invalid JSON makes JSON.parse() throw a SyntaxError.
Use JSON.stringify() to turn a JavaScript value into JSON text:
const person = {
name: 'Flavio',
age: 35
}
const text = JSON.stringify(person)
Pass a third argument to format the output:
JSON.stringify(person, null, 2)
JSON.stringify() does not preserve every JavaScript value. Object properties containing undefined, functions, or symbols are omitted. BigInt values throw unless you provide a custom representation, and circular references also throw.
JSON.parse() accepts an optional second argument called a reviver. It lets you transform parsed values:
const text = '{"name":"Flavio","age":35}'
JSON.parse(text, (key, value) => {
if (key === 'name') {
return `Name: ${value}`
}
return value
})
Always return values you do not want to change. Returning undefined deletes that property from the result. See the MDN JSON.parse() reference for the complete behavior.
Nesting objects
You can organize data in a JSON file using a nested object:
{
"name": {
"firstName": "Flavio",
"lastName": "Copes"
},
"age": 35,
"dogs": [
{ "name": "Roger" },
{ "name": "Syd" }
],
"country": {
"details": {
"name": "Italy"
}
}
}
JSON Schema
While JSON is very flexible right from the start, there are times when you need a bit more rigid organization to keep things in place.
This is where JSON Schema helps. It describes the expected shape and constraints of JSON data so tools can validate it.
Related posts about js: