(string) .
.
:
let user = {
name: "John",
age: 30,
toString() {
return `{name: "${this.name}", age: ${this.age}}`;
}
};
alert(user); // {name: "John", age: 30}
. toString . .
. .
JSON.stringify
JSON (JavaScript Object Notation) . RFC 4627. . JSON / Ruby/PHP/Java .
JSON:
JSON.stringify.JSON.parse.
student JSON.stringify:
let student = {
name: 'John',
age: 30,
isAdmin: false,
courses: ['html', 'css', 'js'],
wife: null
};
let json = JSON.stringify(student);
alert(typeof json); // !
alert(json);
/* JSON-encoded object:
{
"name": "John",
"age": 30,
"isAdmin": false,
"courses": ["html", "css", "js"],
"wife": null
}
*/
JSON.stringify(student) .
JSON-encoded object serialized object stringified object marshalled object. .
:
-
""''.'John'"John". -
"".age:30"age":30.
JSON.stringify .
:
-
{ ... } - (arrays)
[ ... ] - (Primitives):
- (strings),
- ,
- (booleans)
true/false, null.
:
//
alert(JSON.stringify(1)); // 1
// ""
alert(JSON.stringify('test')); // "test"
alert(JSON.stringify(true)); // true
alert(JSON.stringify([1, 2, 3])); // [1,2,3]
JSON.stringify.
:
- Function properties (methods).
- Symbolic keys and values.
- Properties that store
undefined.
let user = {
sayHi() {
//
alert('Hello');
},
[Symbol('id')]: 123, //
something: undefined, //
};
alert(JSON.stringify(user)); // {} ( )
. .
.
:
let meetup = {
title: "Conference",
room: {
number: 23,
participants: ["john", "ann"]
}
};
alert( JSON.stringify(meetup) );
/* :
{
"title":"Conference",
"room":{"number":23,"participants":["john","ann"]},
}
*/
: .
:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: ["john", "ann"]
};
meetup.place = room; // meetup room
room.occupiedBy = meetup; // room meetup
JSON.stringify(meetup); // : Converting circular structure to JSON
(circular reference): room.occupiedBy meetup meetup.place room
Excluding and transforming: replacer
JSON.stringify :
let json = JSON.stringify(value[, replacer, space])
- value
- .
- replacer
- (array) .
- space
- .
JSON.stringify (circular references) JSON.stringify.
.
:
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup room
};
room.occupiedBy = meetup; // room meetup
alert( JSON.stringify(meetup, ['title', 'participants']) );
// {"title":"Conference","participants":[{},{}]}
. participants name .
room.occupiedBy (circular reference):
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup room
};
room.occupiedBy = meetup; // room meetup
alert( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
/*
{
"title":"Conference",
"participants":[{"name":"John"},{"name":"Alice"}],
"place":{"number":23}
}
*/
occupiedBy .
replacer.
undefined .
occupiedBy. occupiedBy undefinrd:
let room = {
number: 23,
};
let meetup = {
title: 'Conference',
participants: [{ name: 'John' }, { name: 'Alice' }],
place: room, // meetup room
};
room.occupiedBy = meetup; // room meetup
alert(
JSON.stringify(meetup, function replacer(key, value) {
alert(`${key}: ${value}`);
return key == 'occupiedBy' ? undefined : value;
})
);
/* key:value pairs that come to replacer:
: [object Object]
title: Conference
participants: [object Object],[object Object]
0: [object Object]
name: John
1: [object Object]
name: Alice
place: [object Object]
number: 23
occupiedBy: [object Object]
*/
replacer . .
this
replacer
.
. {"": meetup}. . ":[object Object]" .
replacer : .
:
JSON.stringify(value, replacer, space) .
. . space .
space = 2 :
let user = {
name: 'John',
age: 25,
roles: {
isAdmin: false,
isEditor: true,
},
};
alert(JSON.stringify(user, null, 2));
/* two-space indents:
{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}
*/
/* JSON.stringify(user, null, 4) :
{
"name": "John",
"age": 25,
"roles": {
"isAdmin": false,
"isEditor": true
}
}
*/
space .
The third argument can also be a string. In this case, the string is used for indentation instead of a number of spaces.
The space parameter is used solely for logging and nice-output purposes.
toString toJSON . JSON.stringify .
:
let room = {
number: 23
};
let meetup = {
title: "Conference",
date: new Date(Date.UTC(2017, 0, 1)),
room
};
alert( JSON.stringify(meetup) );
/*
{
"title":"Conference",
"date":"2017-01-01T00:00:00.000Z", // (1)
"room": {"number":23} // (2)
}
*/
date (1) toJSON .
toJSON room (2):
let room = {
number: 23,
toJSON() {
return this.number;
}
};
let meetup = {
title: "Conference",
room
};
alert( JSON.stringify(room) ); // 23
alert( JSON.stringify(meetup) );
/*
{
"title":"Conference",
"room": 23
}
*/
toJSON JSON.stringify(room) room .
JSON.parse
:
let value = JSON.parse(str, [reviver]);
- str
- .
- reviver
- .
:
//
let numbers = '[0, 1, 2, 3]';
numbers = JSON.parse(numbers);
alert(numbers[1]); // 1
(nested objects):
let userData = '{ "name": "John", "age": 35, "isAdmin": false, "friends": [0,1,2,3] }';
let user = JSON.parse(userData);
alert(user.friends[1]); // 1
.
( ):
let json = `{
name: "John", // mistake: property name without 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
}`;
(comments) .
JSON5 .
JSON .
reviver
meetup \.
:
// title: (meetup title), date: (meetup date)
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
.
JSON.parse:
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str);
alert( meetup.date.getDate() ); // !
! !
meetup.date JSON.parse
reviver JSON.parse
date :
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( meetup.date.getDate() ); // !
:
let schedule = `{
"meetups": [
{"title":"Conference","date":"2017-11-30T12:00:00.000Z"},
{"title":"Birthday","date":"2017-04-18T12:00:00.000Z"}
]
}`;
schedule = JSON.parse(schedule, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( schedule.meetups[1].date.getDate() ); // !
- JSON .
- JSON
null. - JSON.stringify JSON.parse .
- .
-
toJSONJSON.stringify.
<code><pre>10 (plnkr, JSBin, codepen)