Convert a multidimensional javascript array to JSON?
Asked Answered
T

9

41

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

Trichoid answered 19/1, 2009 at 20:47 Comment(0)
B
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.

Bivens answered 19/1, 2009 at 21:1 Comment(2)
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.Isidore
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.Shoot
H
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>
Haematothermal answered 28/12, 2009 at 21:41 Comment(0)
A
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.

Animalism answered 3/6, 2009 at 17:17 Comment(1)
Here's firefox's dev page on JSON support: developer.mozilla.org/en/JSON#Using_JSONPyrogallate
R
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;
}
Recommendatory answered 3/10, 2010 at 13:50 Comment(0)
O
0

You could use the encode function of this library.

Omnidirectional answered 19/1, 2009 at 20:54 Comment(0)
A
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>
Adrenocorticotropic answered 28/5, 2010 at 14:21 Comment(0)
C
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

Cathouse answered 27/9, 2013 at 17:14 Comment(1)
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":""}}}Cathouse
M
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();
}
Manatarms answered 21/7, 2014 at 9:29 Comment(0)
I
-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 = [];
Isidore answered 5/9, 2019 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.