JavaScript JSON parse() metoden
- Forrige side parse()
- Næste side stringify()
- Gå tilbage til forrige niveau JavaScript JSON Reference Manual
定义和用法
JSON.parse() 方法解析字符串并返回 JavaScript 对象。
该字符串必须以 JSON 格式编写。
JSON.parse() 方法可以选择使用函数来转换结果。
实例
例子 1
解析一个字符串(以 JSON 格式编写)并返回一个 JavaScript 对象:
var obj = JSON.parse('{"firstName":"Bill", "lastName":"Gates"}');
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;
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();
Syntax
JSON.parse(string, function)
Parameter value
Parameter | Description |
---|---|
string | Required. A string written in JSON format. |
reviver function |
Optional. A function used to transform the result. Call this function for each item. Any nested objects are transformed before the parent object. If this function returns a valid value, replace the item value with the converted value. If this function returns undefined, delete this item. |
Technical details
Return value: | JSON object, or number. |
---|---|
JavaScript version: | ECMAScript 5 |
Browser supports
Tal i tabellen angiver den første browserversion, der fuldt ud understøtter denne metode.
Metoder | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Relaterede sider
JSON tutorial:JSON introduktion
- Forrige side parse()
- Næste side stringify()
- Gå tilbage til forrige niveau JavaScript JSON Reference Manual