41

What is the best way of converting a multi-dimensional javascript array to JSON?

asked Jan 19, 2009 at 20:47

9 Answers 9

27

Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : http://docs.jquery.com/Getjson

However, you can get an open-source JSON parser and stringifier from the json website :

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

Then, simply include the code and use the JSON.stringify() method on your array.

Jamie Bull
13.6k18 gold badges80 silver badges123 bronze badges
answered Jan 19, 2009 at 21:01
Sign up to request clarification or add additional context in comments.

2 Comments

Down-voted for answering a JavaScript question with a framework/library response. Browsers already support JavaScript so making a 10% effort to program the right way results in much greater than 10% performance. Plus with real JavaScript you won't have to rewrite code to use a newer version of a framework or library.
Just a note: "real" JavaScript (meaning: JavaScript copied from SO or coded on one's own) is not tested nor refined or optimized. You might not want the whole library, but you might want the function. Plus: frameworks like Svelte or others include this kind of library already. Reinventing the wheel is not always a good idea since the resulting quality is unknown.
15

The "best" way has been provided by the other posters. If you don't need the full encoding features of the referenced libraries, and only need to encode simple arrays, then try this:

<!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>
GitaarLAB
14.7k12 gold badges62 silver badges83 bronze badges
answered Dec 28, 2009 at 21:41

Comments

5

Not sure I fully understand your question, but if you are trying to convert the object into a string of JSON then you probably want to look at the native JSON support in all the new browsers. Here's Resig's post on it. For browsers that don't yet support it try the json2.js library. JSON.stringify(obj) will convert your object to a string of JSON.

Sasha Chedygov
132k27 gold badges107 silver badges117 bronze badges
answered Jun 3, 2009 at 17:17

1 Comment

Here's firefox's dev page on JSON support: developer.mozilla.org/en/JSON#Using_JSON
1

This will convert all combinations of arrays within objects and vice versa including function names:

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;
}
p.campbell
101k71 gold badges265 silver badges326 bronze badges
answered Oct 3, 2010 at 13:50

Comments

0

You could use the encode function of this library.

answered Jan 19, 2009 at 20:54

Comments

0

I've modified a bit the code previously provided... because a JSON has this format: [{"object":{"property_1":"value_1","property_2":"value_2"}}]

So, the code would be...

<!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>
LPL
17.1k6 gold badges55 silver badges98 bronze badges
answered May 28, 2010 at 14:21

Comments

0
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));

Try this

Ciarán Bruen
5,36113 gold badges64 silver badges70 bronze badges
answered Sep 27, 2013 at 17:14

1 Comment

Output of this code is {"0":{"title":"Contributory","category":"Plan Features","values":{"0":"checked","1":"checked","2":"checked","3":"checked"},"disabled":{"0":"","1":"","2":"","3":""}},"1":{"title":"Contributory","category":"Plan Features","values":{"0":"checked","1":"checked","2":"checked","3":"checked"},"disabled":{"0":"","1":"","2":"","3":""}},"2":{"title":"Contributory","category":"Plan Features","values":{"0":"checked","1":"checked","2":"checked","3":"checked"},"disabled":{"0":"","1":"","2":"","3":""}}}
0

use this code and very simple develop for more two array

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();
}

and 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();
}
answered Jul 21, 2014 at 9:29

Comments

-1

JavaScript will correctly encode an object:

var a = new Object;
var a = {};

JavaScript will not encode an array:

var a = new Array();
var a = [];
answered Sep 5, 2019 at 22:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.