Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

JSON.parse()

翻譯不完整。請協助 翻譯此英文文件

JSON.parse() 方法把字串解析成 JSON,可對解析過的值進行轉換動作

語法

JSON.parse(text[, reviver])

參數

text
要解析成 JSON 的字串。針對 JSON 語法的描述,請參見 JSON 物件。
reviver 選擇性
為選擇性的參數,用來描述JSON字串中的值該如何被解析並回傳的函式(function)

回傳值

從給定的 JSON text 回傳對應的 Object

Throws

如果解析的字串不是合法的JSON格式會丟出一個 SyntaxError 例外

Examples

Using JSON.parse()

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

使用 reviver 參數

如果reviver有被指定,解析後計算出的值會在回傳前經過轉換。 Specifically, the computed value, and all its properties (beginning with the most nested properties and proceeding to the original value itself), are individually run through the reviver, which is called with the object containing the property being processed as this and with the property name as a string and the property value as arguments. If the reviver function returns undefined (or returns no value, e.g. if execution falls off the end of the function), the property is deleted from the object. Otherwise the property is redefined to be the return value.

Reciver除了描述那些需要被轉換成特定的值之外,其他不須經特別轉換的值請記得也要以原來的值回傳,否則這些值會從回傳的結果物件中刪除。

JSON.parse('{"p": 5}', function(k, v) {
  if (typeof v === 'number') {
    return v * 2;  // return v * 2 for numbers
  }
  return v;        // return everything else unchanged
});

// { p: 10 }

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
  console.log(k); // log the current property name, the last is "".
  return v;       // return the unchanged property value.
});

// 1
// 2
// 4
// 6
// 5
// 3 
// ""

JSON.parse() 不容許尾部有逗號

// 這兩個都會拋出 SyntaxError
JSON.parse('[1, 2, 3, 4, ]');
JSON.parse('{"foo" : 1, }');

規範

規範 狀態 註解
ECMAScript 5.1 (ECMA-262)
The definition of 'JSON.parse' in that specification.
Standard 初始定義。從 JavaScript 1.7 導入。
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'JSON.parse' in that specification.
Standard  
ECMAScript 2017 Draft (ECMA-262)
The definition of 'JSON.parse' in that specification.
Draft  

瀏覽器相容性

特徵 Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本功能 (Yes) 3.5 (1.9.1) 8.0 10.5 4.0
特徵 Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本功能 (Yes) (Yes) 1.0 (1.0) (Yes) (Yes) (Yes)

Gecko-specific notes

Starting Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), a malformed JSON string yields a more detailed error message containing the line and column number that caused the parsing error. This is useful when debugging large JSON data.

JSON.parse('[1, 2, 3, 4,]');
// SyntaxError: JSON.parse: unexpected character at
// line 1 column 13 of the JSON data

See also

文件標籤與貢獻者

 此頁面的貢獻者: matthung0807, iigmir, kuolun
 最近更新: matthung0807,