Convertir matriz a JSON


Tengo una matriz (var cars = []) que contiene unos cuantos enteros. He agregado algunos valores a la matriz, pero ahora necesito enviar esta matriz a una página a través del método .get de jQuery. ¿Cómo puedo convertirlo en un objeto JSON para enviarlo?

Author: Ry-, 2010-02-19

7 answers

Script para compatibilidad con versiones anteriores: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Y llamar:

var myJsonString = JSON.stringify(yourArray);

Nota: El objeto JSON es ahora parte de la mayoría de los navegadores web modernos (IE 8 y arriba). Véase caniuse para la lista completa. El crédito va a: @ Spudley por su comentario a continuación

 565
Author: JonoW,
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-03-28 06:55:32

Lo hice de esa manera:

Si tengo:

var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;

var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);

Para convertir pluginArrayArg (que es una matriz javascript pura) en una matriz JSON:

var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
 57
Author: Stancho Stanchev,
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-01-04 13:35:35

Wow, parece que ahora es mucho más fácil... 3 maneras de hacerlo:

json = { ...array };

json = Object.assign({}, array);

json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
 21
Author: Eduardo Sganzerla,
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-12-19 03:39:15

Decidí usar la biblioteca json2 y recibí un error sobre "estructuras de datos cíclicas".

Lo resolví diciéndole a json2 cómo convertir mi objeto complejo. No solo funciona ahora, sino que también he incluido solo los campos que necesito. Así es como lo hice:

OBJ.prototype.toJSON = function (key) {
       var returnObj = new Object();
       returnObj.devid = this.devid;
       returnObj.name = this.name;
       returnObj.speed = this.speed;
       returnObj.status = this.status;
       return returnObj;
   }
 11
Author: Paulo Pedroso,
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
2012-06-22 12:42:39

O intente definir la matriz como un objeto. (var cars = {};) Entonces no hay necesidad de convertir a json. Esto podría no ser práctico en su ejemplo, pero funcionó bien para mí.

 11
Author: think win win,
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-09-03 20:23:35

En JavaScript, puede usar JSON.stringify para convertir una matriz o valores en una cadena con formato JSON.

var output = {}
output[0] = "a";
output[1] = "b";
output[2] = "c";

console.log( JSON.stringify(output) );
 0
Author: Pankaj Mandale,
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-10-16 15:26:29

Si solo tiene 1 objeto como el que pidió, lo siguiente funcionará.

var x = [{'a':'b'}];
var b= JSON.stringify(x);
var c = b.substring(1,b.length-1);
JSON.parse(c); 
 0
Author: Mahmoud ihmaid,
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-02 19:25:50