JavaScript JSON parse() method

定义和用法

JSON.parse() 方法解析字符串并返回 JavaScript 对象。

该字符串必须以 JSON 格式编写。

JSON.parse() 方法可以选择使用函数来转换结果。

实例

例子 1

解析一个字符串(以 JSON 格式编写)并返回一个 JavaScript 对象:

var obj = JSON.parse('{"firstName":"Bill", "lastName":"Gates"}');

Try it yourself

Example 2

How to use the reviver function:

/* Replace the "city" value with uppercase: */
var text = '{ "name":"Bill", "age":"19", "city":"Seattle"}';
var obj = JSON.parse(text, function (key, value) {
  if (key == "city") {
    return value.toUpperCase();
  } else {
    return value;
  }
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.city;

Try it yourself

Example 3

Parse JSON received from the server:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

Try it yourself

See json_demo.txt

Syntax

JSON.parse(string, function)

Parameter value

Parameter Description
string Required. A string written in JSON format.
reviver function

Optional. A function used to convert the result. Call this function for each item. Any nested objects are converted before the parent object.

If this function returns a valid value, then replace the item value with the converted value.

If this function returns undefined, then delete this item.

Technical details

Return value: JSON object, or number.
JavaScript version: ECMAScript 5

Browser supports

The numbers in the table indicate the first browser version that fully supports this method.

Method Chrome IE Firefox Safari Opera
parse() 4.0 8.0 3.5 4.0 11.5

Related pages

JSON tutorial:JSON introduction