English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON viene utilizzato per scambiare dati con il server web. Quando si ricevono dati dal server web, i dati sono sempre stringhe.
Il metodo JSON.parse() analizza una stringa JSON per costruire un valore JavaScript o un oggetto descritto dalla stringa.
Sintassi:
JSON.parse(text, reviver)
Il primo parametro specifica la stringa da解析are come JSON.
Il secondo parametro opzionale specifica una funzione da eseguire prima di ogni proprietà del valore di ritorno.
Supponiamo di ricevere il seguente testo dal server web:
'{"name":"Seagull", "age":22, "city":"New Delhi"}'
Utilizzando il metodo JSON.parse(), possiamo convertire il testo JSON in un oggetto JavaScript:
var myObj = JSON.parse('{"name":"Seagull", "age":22, "city":"New Delhi"}');测试看看‹/›
Puoi richiedere JSON dal server utilizzando una richiesta AJAX.
Se il rispondimento del server è scritto in formato JSON, è possibile convertire la stringa in un oggetto JavaScript.
以下示例请求文件demo.json并解析响应:
var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var myObj = JSON.parse(this.responseText); document.getElementById("output").innerHTML = myObj.name; } }; httpRequest.open("GET", "demo.json", true); httpRequest.send();测试看看‹/›
JSON.parse()在从数组派生的JSON上使用方法,该方法将返回JavaScript数组,而不是JavaScript对象。
以下示例请求文件json_array.txt并解析响应:
var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var myArr = JSON.parse(this.responseText); document.getElementById("output").innerHTML = myArr[0]; } }; httpRequest.open("GET", "json_array.txt", true); httpRequest.send();测试看看‹/›
JSON中不允许使用日期对象。
如果需要包括日期,则将其写为字符串,然后稍后将其转换回日期对象。
var myJSON = '{"name":"Seagull", "birth":"1997-11-10", "city":"New Delhi"}'; var myObj = JSON.parse(myJSON); myObj.birth = new Date(myObj.birth); document.getElementById("output").innerHTML = myObj.name + " DOB is" + myObj.birth;测试看看‹/›
注意:将字符串转换为本地对象称为解析,而将本地对象转换为可以在网络上传输的字符串称为字符串化。