Your program has the object { name: 'Budi', age: 17 }. When you send it to a server (a computer that stores a site's data), it arrives there as text: {"name":"Budi","age":17}. The two look alike, but the second one is only a row of characters. Servers, localStorage (a storage place in the browser) and other programming languages cannot read JavaScript objects. But all of them can read text.
That text format is called JSON (short for JavaScript Object Notation). JSON is a format for storing and sending data. It looks like a JavaScript object, but it is only text. JavaScript has two tools for JSON. JSON.stringify turns an object into JSON text. JSON.parse turns JSON text back into an object.
Object to text, text to object
The example below turns the object student into JSON text, then turns that text back into an object:
const student = {
name: 'Budi',
age: 17,
hobbies: ['coding', 'reading'],
}
const json = JSON.stringify(student)
console.log(json)
console.log('typeof json:', typeof json)
console.log('json.name:', json.name)
const back = JSON.parse(json)
console.log('back.name:', back.name)
JSON.stringify(student)gives JSON text.console.log(json)prints{"name":"Budi","age":17,"hobbies":["coding","reading"]}.typeof jsonisstring. The content ofjsonlooks like an object, but it is only text.- That is why
json.namegivesundefined: text has nonameproperty. JSON.parse(json)reads that text and builds a new object. In that new object,back.nameisBudiagain.JSON.stringify(student, null, 2)makes the same JSON text, but tidy: each property on its own line, indented by 2 spaces, so it is easy to read. Thenullin the middle means that every property goes into the text.
JSON.stringify and JSON.parse do not change the original value: they give you a new one. So store the result in a variable, or write return JSON.stringify(obj) directly in a function. In the exercise, do not type the JSON text yourself. JSON.stringify can turn any object into text, while text that you type fits only one example.
The rules for writing JSON
JSON is stricter than a JavaScript object. Here is an example of valid JSON text:
{
"name": "Budi",
"age": 17,
"active": true,
"hobbies": ["reading", "coding"],
"address": null
}
- Property names always use double quotes:
"name", notnameor'name'. Strings use double quotes too:"Budi". - The only values allowed are strings, numbers, booleans (
true/false),null, arrays and objects. - No comma is allowed after the last item, and no comments are allowed.
Text that breaks these rules makes JSON.parse throw a SyntaxError.
What gets lost or changed in stringify
Not every value can go into JSON. Look at what JSON.stringify gives for an object that holds a function, undefined and a date:
const data = {
name: 'Budi',
greet() { return 'Hello' },
nickname: undefined,
born: new Date('2008-05-17'),
}
JSON.stringify(data)
// '{"name":"Budi","born":"2008-05-17T00:00:00.000Z"}'
- Functions (
greet) andundefined(nickname) are removed silently, with no error, because JSON has neither kind of value. Inside an array, a function orundefinedbecomesnull. - A
Date(a date object) turns into date text. AfterJSON.parsethe value is still text, not aDate. If you need a date again, make a new one withnew Date(back.born)(backis the result ofJSON.parse).
⚠️ Text mistaken for an object, and the other way round
- Data from a server or from localStorage arrives as text.
data.namegivesundefineduntil you turn that text into an object withJSON.parse. - One wrong quote in text from outside makes
JSON.parsethrow an error and stop the program. WrapJSON.parseintry...catchwhen you did not make the data yourself. - When you join JSON text by hand, as in
'{"name":"' + name + '"}', it is easy to get a quote wrong. Build the object, then letJSON.stringifywrite the text.
TL;DR: JSON (JavaScript Object Notation) is a text format for storing and sending data. It looks like a JavaScript object. JSON.stringify(obj) turns an object into text, and JSON.parse(text) turns that text back into an object. The result of stringify is only a string, so you can read the object's properties only after you parse the text. In JSON, property names and strings use double quotes, and there is no comma after the last item. stringify removes functions and undefined silently, and a Date (a date object) becomes text.
⚡ Object to text, text to object
Write:
const json = JSON.stringify(student)
console.log(json.name) // ?
const back = JSON.parse(json)
console.log(back.name) // Budi
Guess first: student is an object with name: 'Budi', and JSON.stringify turns it into text. What does json.name give?
undefined. The result of JSON.stringify is only text, and text has no name property.
Meaning: JSON is a text format for data. It looks like a JavaScript object. An object is turned into JSON text so that it can be stored or sent. JSON.parse reads that text and builds a new object, so back.name is Budi.
⚡ JSON is stricter
Write:
{
"name": "Budi",
"age": 17,
"active": true
}
Meaning: The rules of JSON are stricter than the rules of a JavaScript object. Property names and strings always use double quotes. No comma is allowed after the last item, and no comments are allowed. If the text breaks these rules, JSON.parse throws a SyntaxError.
⚡ What gets lost in stringify
Write:
const data = {
name: 'Budi',
greet() { return 'Hello' },
nickname: undefined,
}
JSON.stringify(data)
Guess first: what happens to greet and nickname in the text?
Both are removed silently. The result is only '{"name":"Budi"}', because JSON has no functions and no undefined.
Meaning: JSON.stringify removes values that JSON does not have. A Date (a date object) turns into date text, and after JSON.parse it is still text.