JSON methods, toJSON

JSON.stringify

  • JSON.stringify to convert objects into JSON.

  • JSON.parse to convert JSON back into an object.

let student = {
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  wife: null
};

let json = JSON.stringify(student);

alert(typeof json); // we've got a string!

alert(json);
/* JSON-encoded object:
{
  "name": "John",
  "age": 30,
  "isAdmin": false,
  "courses": ["html", "css", "js"],
  "wife": null
}
*/
  • 字串使用 "" 'John' 變成 "John"。

  • 屬性名稱也是"" age:30 變成 "age":30。

支援 JSON 的類型

  • Objects { ... }

  • Arrays [ ... ]

  • Primitives:

    • strings,

    • numbers,

    • boolean values true/false,

    • null.

JSON.stringify 不支援

  • Function properties (methods).

  • Symbolic properties.

  • Properties that store undefined.

Excluding and transforming: replacer

Formatting: spacer

Custom “toJSON”

就像物件使用 toString 轉換成 string,物件也可以使用 toJSON 轉換成 JSON。

JSON.parse

Using reviver

Last updated

Was this helpful?