JavaScript JSON parse()-Methode
- Vorherige Seite parse()
- Nächste Seite stringify()
- Zurück zur Oberfläche JavaScript JSON Referenzhandbuch
定义和用法
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 convert the result. This function is called for each item. Any nested objects are converted 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 support
Die Zahlen in der Tabelle weisen auf die erste Browser-Version hin, die diese Methode vollständig unterstützt.
Methode | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Verwandte Seiten
JSON-Tutorial:Einführung in JSON
- Vorherige Seite parse()
- Nächste Seite stringify()
- Zurück zur Oberfläche JavaScript JSON Referenzhandbuch