example array javascript arrays json

array - Convertir una matriz javascript multidimensional a JSON?



json array example javascript (8)

¿Cuál es la mejor forma de convertir una matriz javascript multidimensional en JSON?



No estoy seguro de entender por completo su pregunta, pero si está tratando de convertir el objeto en una cadena de JSON, entonces probablemente quiera ver el soporte nativo de JSON en todos los navegadores nuevos. Aquí está la publicación de Resig. Para los navegadores que aún no lo admiten, pruebe la biblioteca json2.js . JSON.stringify (obj) convertirá su objeto en una cadena de JSON.


Esto convertirá todas las combinaciones de matrices dentro de los objetos y viceversa, incluidos los nombres de las funciones:

function isArray(a){var g=a.constructor.toString(); if(g.match(/function Array()/)){return true;}else{return false;} } function objtostring(o){var a,k,f,freg=[],txt; if(typeof o!=''object''){return false;} if(isArray(o)){a={''t1'':''['',''t2'':'']'',''isarray'':true} }else {a={''t1'':''{'',''t2'':''}'',''isarray'':false}}; txt=a.t1; for(k in o){ if(!a.isarray)txt+="''"+k+"'':"; if(typeof o[k]==''string''){txt+="''"+o[k]+"'',"; }else if(typeof o[k]==''number''||typeof o[k]==''boolean''){txt+=o[k]+","; }else if(typeof o[k]==''function''){f=o[k].toString();freg=f.match(/^function/s+(/w+)/s*/(/); if(freg){txt+=freg[1]+",";}else{txt+=f+",";}; }else if(typeof o[k]==''object''){txt+=objtostring(o[k])+","; } }return txt.substr(0,txt.length-1)+a.t2; }


He modificado un poco el código proporcionado anteriormente ... porque un JSON tiene este formato: [{"object":{"property_1":"value_1","property_2":"value_2"}}]

Entonces, el código sería ...

<!DOCTYPE html> <html> <head> <title>Simple functions for encoding Javascript arrays into JSON</title> <script type="text/javascript"> window.onload = function(){ var a = [[''property_1'',''value_1''],[''property_2'', ''value_2'']]; alert("Comienzo..., paso ////"+a+"////// a formato JSON"); var jsonSerialized = array2dToJson(a, ''object''); alert(jsonSerialized); }; // Estructura de JSON [{"object":{"property_1":"value_1","property_2":"value_2"}}] function array2dToJson(a, p, nl) { var i, j, s = ''[{"'' + p + ''":{''; nl = nl || ''''; for (i = 0; i < a.length; ++i) { s += nl + array1dToJson(a[i]); if (i < a.length - 1) { s += '',''; } } s += nl + ''}}]''; return s; } function array1dToJson(a, p) { var i, s = ''''; for (i = 0; i < a.length; ++i) { if (typeof a[i] == ''string'') { s += ''"'' + a[i] + ''"''; } else { // assume number type s += a[i]; } if (i < a.length - 1) { s += '':''; } } s += ''''; if (p) { return ''{"'' + p + ''":'' + s + ''}''; } return s; } </script> </head> <body> <h1>Convertir un Array a JSON...</h1> </body> </html>


var t = {} for(var i=0;i<3;i++) { var _main = {}; var _dis = {} var _check = {}; _main["title"] = ''test''; _main["category"] = ''testing''; _dis[0] = ''''; _dis[1] = ''''; _dis[2] = ''''; _dis[3] = ''''; _check[0] = ''checked''; _check[1] = ''checked''; _check[2] = ''checked''; _check[3] = ''checked''; _main[''values''] = _check; _main[''disabled''] = _dis; t[i] = _main; } alert(JSON.stringify(t));

Prueba esto


La mayoría de los marcos de JavaScript populares tienen funciones de utilidad JSON incluidas. Por ejemplo, jQuery tiene una función que llama directamente a una url y carga el resultado JSON como un objeto: http://docs.jquery.com/Getjson

Sin embargo, puede obtener un analizador y secuenciador JSON de código abierto desde el sitio web json :

https://github.com/douglascrockford/JSON-js

Luego, simplemente incluya el código y use el método JSON.stringify () en su matriz.


utilice este código y desarrollo muy simple para más dos matriz

function getJSON(arrayID,arrayText) { var JSON = "["; //should arrayID length equal arrayText lenght and both against null if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) { for (var i = 0; i < arrayID.length; i++) { JSON += "{"; JSON += "text:''" + arrayText[i] + "'',"; JSON += "id:''" + arrayID[i] + "''"; JSON += "},"; } } JSON += "]" JSON = Function("return " + JSON + " ;"); return JSON(); }

y 3 array

function getJSON(arrayID, arrayText, arrayNumber) { var JSON = "["; if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) { for (var i = 0; i < arrayID.length; i++) { JSON += "{"; JSON += "text:''" + arrayText[i] + "'',"; JSON += "id:''" + arrayID[i] + "'',"; JSON += "number:''" + arrayNumber[i] + "''"; JSON += "},"; } } JSON += "]" JSON = Function("return " + JSON + " ;"); return JSON(); }


La "mejor" manera ha sido proporcionada por los otros carteles. Si no necesita las características de codificación completa de las bibliotecas a las que se hace referencia, y solo necesita codificar las matrices simples, intente esto:

<!DOCTYPE html> <html> <head> <title>Simple functions for encoding Javascript arrays into JSON</title> <script type="text/javascript"> window.onload = function() { var a = [ [0, 1, ''2'', 3], [''0'', ''1'', 2], [], [''mf'', ''cb''] ], b = [ 0, ''1'', ''2'', 3, ''woohoo!'' ]; alert(array2dToJson(a, ''a'', ''/n'')); alert(array1dToJson(b, ''b'')); }; function array2dToJson(a, p, nl) { var i, j, s = ''{"'' + p + ''":[''; nl = nl || ''''; for (i = 0; i < a.length; ++i) { s += nl + array1dToJson(a[i]); if (i < a.length - 1) { s += '',''; } } s += nl + '']}''; return s; } function array1dToJson(a, p) { var i, s = ''[''; for (i = 0; i < a.length; ++i) { if (typeof a[i] == ''string'') { s += ''"'' + a[i] + ''"''; } else { // assume number type s += a[i]; } if (i < a.length - 1) { s += '',''; } } s += '']''; if (p) { return ''{"'' + p + ''":'' + s + ''}''; } return s; } </script> </head> <body> </body> </html>