Analizar JSON en JavaScript? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Quiero analizar una cadena JSON en JavaScript. La respuesta es algo así como

var response = '{"result":true,"count":1}';

¿Cómo puedo obtener los valores result y count de esto?

Author: Taryn, 2011-02-08

16 answers

La mayoría de los navegadores son compatibles JSON.parse(), que se define en ECMA-262 5th Edition (la especificación en la que se basa JavaScript). Su uso es simple:

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);

alert(obj.count);

/* or ES6 */

const json = '{"result":true,"count":1}' || {};
const { result, count } = JSON.parse(json);
alert(result);
alert(count);

Para los navegadores que no lo hacen puedes implementarlo usando json2.js.

Como se indica en los comentarios, si ya está utilizando jQuery, hay una función $.parseJSON que se asigna a JSON.parse si está disponible o una forma de eval en navegadores más antiguos. Sin embargo, esto realiza comprobaciones adicionales e innecesarias que también se realizan por JSON.parse, así que para el mejor rendimiento en todos los sentidos, recomiendo usarlo de la siguiente manera:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

Esto asegurará que use native JSON.parse inmediatamente, en lugar de hacer que jQuery realice comprobaciones de cordura en la cadena antes de pasarla a la función de análisis nativa.

 1875
Author: Andy E,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 10:13:09

En primer lugar, debe asegurarse de que el código JSON sea válido.

Después de eso, recomendaría usar una biblioteca JavaScript como jQuery o Prototype si puede, porque estas cosas se manejan bien en esas bibliotecas.

Por otro lado, si no desea usar una biblioteca y puede dar fe de la validez del objeto JSON, simplemente envolver la cadena en una función anónima y usar la función eval.

Esto no se recomienda si está recibiendo el objeto JSON de otra fuente que no es absolutamente confiable porque la función eval permite código renegado si se quiere.

Aquí hay un ejemplo de uso de la función eval:

var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);

Si usted controla qué navegador se está utilizando o no está preocupado de la gente con un navegador más antiguo, siempre se puede utilizar el JSON.método parse.

Esta es realmente la solución ideal para el futuro.

 90
Author: Clarence Fredericks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-28 11:17:39

Si está obteniendo esto de un sitio externo, podría ser útil usar getJSON de jQuery. Si es una lista, puede iterar a través de ella con $.cada

$.getJSON(url, function (json) {
    alert(json.result);
    $.each(json.list, function (i, fb) {
        alert(fb.result);
    });
});
 49
Author: milestyle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 21:30:42

Si desea utilizar JSON 3 para navegadores más antiguos, puede cargarlo condicionalmente con:

<script>
    window.JSON || 
    document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>

Ahora el objeto estándar window.JSON está disponible para usted sin importar qué navegador esté ejecutando un cliente.

 32
Author: huwiler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 21:30:57

El siguiente ejemplo lo aclarará:

var jsontext   = '{"name":"x","age":"11"}';
var getContact = JSON.parse(jsontext);
document.write(getContact.name + ", " + getContact.age);

// Output: x, 11

O

También puede usar la función eval. El siguiente ejemplo está usando la función eval:

var jsontext   = '{"name":"x","age":"11"}';
var getContact = eval('(' + jsontext + ')');
document.write(getContact.name + ", " + getContact.age);

// Output: x, 11

Dado que la función JSON.parse es más segura y se ejecuta más rápido que la función eval, le recomiendo usar la función JSON.parse.

 31
Author: Joke_Sense10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 14:00:53

Puede usar la función eval como en algunas otras respuestas. (No olvides los aparatos extra.) Sabrá por qué cuando profundice), o simplemente use la función jQuery parseJSON:

var response = '{"result":true , "count":1}'; 
var parsedJSON = $.parseJSON(response);

O

Puede usar este código a continuación.

var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);

Y puedes acceder a los campos usando jsonObject.result y jsonObject.count.

 25
Author: Teja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 13:59:43

Si pasa una variable string (una cadena JSON bien formada) a JSON.analizar desde MVC @ Viewbag que tiene doublequote,'"', como comillas, debe procesarlo antes de JSON.analizar (jsonstring)

    var jsonstring = '@ViewBag.jsonstring';
    jsonstring = jsonstring.replace(/&quot;/g, '"');  
 25
Author: Jenna Leaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:12:57

La forma más fácil usando el método parse():

var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);

Este es un ejemplo de cómo obtener valores:

var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
 23
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-20 00:58:42

Sin usar una biblioteca puede usar eval - la única vez que debe usar. Sin embargo, es más seguro usar una biblioteca.

Eg...

var response = '{"result":true , "count":1}';

var parsedJSON = eval('('+response+')');

var result=parsedJSON.result;
var count=parsedJSON.count;

alert('result:'+result+' count:'+count);
 19
Author: El Ronnoco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-08 16:45:37

JSON.parse () convierte cualquier cadena JSON pasada a la función, en un objeto JSON.

Para una mejor comprensión, presione F12 para abrir el elemento Inspect de su navegador, y vaya a la consola para escribir los siguientes comandos:

var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.

Ahora ejecute el comando:

console.log(JSON.parse(response));

Obtendrá la salida como Objeto {result: true, count: 1}.

Para usar ese objeto, puedes asignarlo a la variable, digamos obj:

var obj = JSON.parse(response);

Ahora usando obj y el dot(.) operador puede acceder a las propiedades del objeto JSON.

Intenta ejecutar el comando

console.log(obj.result);
 19
Author: Pushkar Kathuria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:11:55

Si quieres

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

Puede acceder a los elementos JSON mediante JSONObject con (.) punto:

JsonObject.result;
JsonObject.count;
 17
Author: user5676965418,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:10:07

Pensé que JSON.parse(myObject) funcionaría. Pero dependiendo de los navegadores, podría valer la pena usar eval('('+myObject+')'). El único problema que puedo recomendar es la lista de niveles múltiples en JSON.

 11
Author: ha9u63ar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-04 10:38:37

Una manera fácil de hacerlo:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)
 9
Author: yassine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:13:11

Si utiliza jQuery, es simple:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
 4
Author: legendJSLC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 14:01:18

Si utiliza Dojo Toolkit :

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});
 4
Author: Brendon-Van-Heyzen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:13:49

Como han mencionado muchos otros, la mayoría de los navegadores soportan JSON.parse y JSON.stringify.

Ahora, también me gustaría añadir que si está utilizando AngularJS (que recomiendo encarecidamente), entonces también proporciona la funcionalidad que necesita:

var myJson = '{"result": true, "count": 1}';
var obj = angular.fromJson(myJson);//equivalent to JSON.parse(myJson)
var backToJson = angular.toJson(obj);//equivalent to JSON.stringify(obj)

Solo quería añadir las cosas sobre AngularJS para proporcionar otra opción. TENGA en cuenta que AngularJS no es compatible oficialmente con Internet Explorer 8 (y versiones anteriores, para el caso), aunque a través de la experiencia de la mayoría de las cosas parece funciona bastante bien.

 4
Author: user2359695,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 21:14:40