Método JavaScript JSON parse()
Exemplo
Analise uma string (escrita no formato JSON) e retorne um objeto JavaScript:
var obj = JSON.parse('{"firstName":"John", "lastName":"Doe"}');
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
O método JSON.parse() analisa uma string e retorna um objeto JavaScript.
A string deve ser escrita no formato JSON.
O método JSON.parse() pode opcionalmente transformar o resultado com uma função.
Suporte ao navegador
Os números na tabela especificam a primeira versão do navegador que oferece suporte total ao método.
Method | |||||
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Sintaxe
JSON.parse(string, function)
Valores de parâmetro
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.
|
Detalhes técnicos
Valor de retorno: | Um objeto JSON ou matriz |
---|---|
Versão JavaScript: | ECMAScript 5 |
Mais exemplos
Exemplo
Como usar a função reviver :
/*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;
Exemplo
Analisando JSON recebido do servidor:
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();
Dê uma olhada em json_demo.txt
Páginas relacionadas
Tutorial JSON: Introdução ao JSON