Convert a multidimensional javascript array to JSON?

Viewed 91024

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

9 Answers

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>

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.

JavaScript will correctly encode an object:

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

JavaScript will not encode an array:

var a = new Array();
var a = [];
Related