[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse [Back]  [Original]

JSON.parse() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

JSON.parse()

*

20157

*

JSON.parse() JSON JavaScript reviver

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// 42

console.log(obj.result);
// true

js
JSON.parse(text)
JSON.parse(text, reviver)

text

JavaScript JSON JSON

reviver

key

value

context

reviver value

source

JSON

JSON text ObjectArraystringnumberboolean null

SyntaxError

JSON

JSON.parse() JSON JSON JavaScript "__proto_" JSON JavaScript JSON

reviver

reviver reviver

reviver this reviver this key value context reviver undefined reviver

JSON.stringify() replacer reviver key value JSON reviver key value

reviver

js
const transformedObj1 = JSON.parse('[1,5,{"s":1}]', (key, value) =>
  typeof value === "object" ? undefined : value,
);

console.log(transformedObj1); // undefined

key JSON reviver

reviver JSON JavaScript BigInt

context.source JSON

js
const bigJSON = '{"gross_gdp": 12345678901234567890}';
const bigObj = JSON.parse(bigJSON, (key, value, context) => {
  if (key === "gross_gdp") {
    // 
    return BigInt(context.source);
  }
  return value;
});

JSON.parse()

js
JSON.parse("{}"); // {}
JSON.parse("true"); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse("null"); // null

reviver

js
JSON.parse(
  '{"p": 5}',
  (key, value) =>
    typeof value === "number"
      ? value * 2 //  value * 2
      : value, // 
);
// { p: 10 }

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
  console.log(key);
  return value;
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""

JSON.stringify() replacer reviver

JSON.stringify() replacer

js
// Map 
// 
const map = new Map([
  [1, "one"],
  [2, "two"],
  [3, "three"],
]);

const jsonText = JSON.stringify(map, (key, value) =>
  value instanceof Map ? Array.from(value.entries()) : value,
);

console.log(jsonText);
// [[1,"one"],[2,"two"],[3,"three"]]

const map2 = JSON.parse(jsonText, (key, value) =>
  Array.isArray(value) && value.every(Array.isArray) ? new Map(value) : value,
);

console.log(map2);
// Map { 1 => "one", 2 => "two", 3 => "three" }

JSON

  • registry Map

JSON

JSON.parse JSON SyntaxError

JSON

js
JSON.parse("[1, 2, 3, 4, ]");
// SyntaxError: Unexpected token ] in JSON at position 13

JSON.parse('{"foo": 1, }');
// SyntaxError: Unexpected token } in JSON at position 12

JSON

js
JSON.parse("{'foo': 1}");
// SyntaxError: Unexpected token ' in JSON at position 1

JSON.parse("'string'");
// SyntaxError: Unexpected token ' in JSON at position 0

JavaScript JSON JavaScript JSON

js
JSON.parse('{"foo": 1}'); // OK
JSON.parse("{\"foo\": 1}"); // OK

ECMAScript 2027 LanguageSpecification
# sec-json.parse


Web Proxy Viewer  |  New URL  |  Original Page