Basics JSON is a string format '{"name": "Juha"}' The data is only JSON when it is in a string format Inside the JSON string there is a JSON object literal {"name": "Juha"} JS object can be created from JSON object literal const person = {"name": "Juha"} JSON string is named also a "JSON-encoded" OR "serialized" OR "stringified" OR "marshalled" object Strings use double quotes. No single quotes or backticks in JSON. 'John' becomes "John" Object property names are double-quoted. So age:30 becomes "age":30 . JSON is needed to transmit JS objects via http, as http does not work with JS objects, but works with text JSON.stringify() JSON.stringify() converts objects into JSON
JSON.stringify(1) // "1"
JSON.stringify('test') // "test"
JSON.stringify(true) // "true"
JSON.stringify([1, 2, 3]) // "[1,2,3]"
let student = {
name: 'John',
age: 30,
isAdmin: false,
courses: ['HTML', 'css', 'JavaScript'],
wife: null
};
JSON.stringify(student);
// "{"name":"John","age":30,"isAdmin":false,"courses":["html","css","js"],"wife":null}"
Ignores methods, symbolics, properties with undefined
let user = {
sayHi() { alert("Hello") }, // ignored
[Symbol("id")]: 123, // ignored
something: undefined // ignored
}
JSON.stringify(user) // "{}" (empty object)
Nested objects are supported
let meetup = {
title: "Conference",
room: {
number: 23,
participants: ["john", "ann"]
}
}
JSON.stringify(meetup) // "{"title":"Conference", "room":{"number":23,"participants":["john","ann"]},}"
No circular references
let room = { number: 23 }
let meetup = { title: "Conference", participants: ["john", "ann"] }
meetup.place = room;
room.occupiedBy = meetup;
JSON.stringify(meetup); // Error: Converting circular structure to JSON
Optional parameters JSON.stringify(value, [replacerFunction(key, value) {} || array, space]) value - A value to encode array of properties to encode OR a mapping function function(key, value). If we pass an array of properties to it, only these properties will be encoded. space - amount of space to use for formatting
let room = {number: 23};
let meetup = { title: "Conference", participants: [{name: "John"}, {name: "Alice"}], place: room};
room.occupiedBy = meetup; // room references meetup
JSON.stringify(meetup, ['title', 'participants']) // {"title":"Conference","participants":[{},{}]}
JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) // "{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}"
let room = {number: 23};
let meetup = { title: "Conference", participants: [{name: "John"}, {name: "Alice"}], place: room};
room.occupiedBy = meetup; // room references meetup
JSON.stringify(meetup, ['title', 'participants']) // {"title":"Conference","participants":[{},{}]}
JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) // "{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}"
function replacerFunction(key, value) {...} return a value OR replaced value return undefined to exclude property / value value of "this" inside replacer is the object that contains the current property The first call is special the first (key, value) pair has an empty key, and the value is the target object as a whole
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}
JSON.stringify(foo, replacer) // "{\"week\":45,\"month\":7}"
Space used for nice - output purposes
let user = {name: "John", age: 25, roles: { isAdmin: false, isEditor: true }}
JSON.stringify(user, null, 4)
"{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}"
JSON.parse()
let userData = '{ "name": "John", "age": 35, "isAdmin": false, "friends": [0,1,2,3] }';
JSON.parse(userData); // {name: "John", age: 35, isAdmin: false, friends: Array(4)}
Incorrect JSON objects and arrays can be included, but they must obey the same JSON format comments trailing commas are not allowed single quotes are not allowed
let json = `{
name: "John", // mistake: property name w/o quotes
"surname": 'Smith', // mistake: single quotes in value (must be double)
'isAdmin': false // mistake: single quotes in key (must be double)
"birthday": new Date(2000, 2, 3), // mistake: no "new" is allowed, only bare values
"friends": [0,1,2,3] // here all fine
}`;
Reviver function JSON.parse(text, function reviver(key, value) {}) returns a value OR replaced value returns undefined to exclude property / value value of "this" inside replacer is the object that contains the current property The first call is special. the first (key, value) pair has an empty key, and the value is the target object as a whole
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meeting = JSON.parse(str);
meeting.date.getDate(); // Error! because date value is not a Date object but the string
meeting= JSON.parse(str, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
meeting.date.getDate() //30 // works!