JavaScript JSON parse() Metodo
Esempio
Analizza una stringa (scritta in formato JSON) e restituisce un oggetto JavaScript:
var obj = JSON.parse('{"firstName":"John", "lastName":"Doe"}');
Altri esempi "Provalo da solo" di seguito.
Definizione e utilizzo
Il metodo JSON.parse() analizza una stringa e restituisce un oggetto JavaScript.
La stringa deve essere scritta in formato JSON.
Il metodo JSON.parse() può facoltativamente trasformare il risultato con una funzione.
Supporto browser
I numeri nella tabella specificano la prima versione del browser che supporta completamente il metodo.
Method | |||||
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Sintassi
JSON.parse(string, function)
Valori dei parametri
Parameter | Description |
---|---|
string | Required. A string written in JSON format |
reviver function | Optional. A function used to transform the result. The function is called for each item. Any nested objects are transformed before the parent.
|
Dettagli tecnici
Valore di ritorno: | Un oggetto JSON o un array |
---|---|
Versione JavaScript: | ECMAScript 5 |
Altri esempi
Esempio
Come utilizzare la funzione ravviva :
/*replace the value of "city" to upper case:*/
var text =
'{ "name":"John", "age":"39", "city":"New York"}';
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;
Esempio
Analisi JSON ricevuto dal 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();
Dai un'occhiata a json_demo.txt
Pagine correlate
Esercitazione JSON: Introduzione a JSON