gberg927
gberg927

Reputation: 1686

Parse JSON into MuliDimensional Array JS

I have a JSON file that I would like to create an multi-dimensional array from. This information is stored in a JSON file.

Here is the JSON data.

{
  "table": {
    "columnNames": ["column1", "column2", "column3", "column4"],
    "columnTypes": ["String", "String", "String", "String"],
    "rows": [
      ["data00", "data01", "data02", "data03"],
      ["data10", "data11", "data12", "data13"],
      ["data20", "data21", "data22", "data23"],
      ["data30", "data31", "data32", "data33"]
     ]
   }
}

I need to create an array of arrays from the objects in the "rows" section.

Any help would be appreciated!

Thanks!!!

Upvotes: 1

Views: 1749

Answers (3)

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

The rows section already contains an array of arrays, so just use:

var result = JSON.parse('{
  "table": {
  "columnNames": ["column1", "column2", "column3", "column4"],
  "columnTypes": ["String", "String", "String", "String"],
  "rows": [
    ["data00", "data01", "data02", "data03"],
    ["data10", "data11", "data12", "data13"],
    ["data20", "data21", "data22", "data23"],
    ["data30", "data31", "data32", "data33"]
   ]
  }
}');

var rows = result.table.rows;

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

You first need to convert the string to JS object.

Use json2.js from http://www.json.org/js.html

Please keep in mind that you need to add json2.js if you consider to support old browsers. Newer browser has built-in support for JSON

And deserialize the string to object

var myObject = JSON.parse(myJSONtext);

And now you can access

myObject.table.rows[1][2]; // yields data12

Upvotes: 0

Pointy
Pointy

Reputation: 413702

Once you parse the JSON, the "table.rows" property will already be a multi-dimensional array (2 dimensions, to be specific). All you have to do is access it:

var array2D = parsed.table.rows;

As to parsing, you should probably use something like Crockford's parser:

var parsed = JSON.parse(rawStringOfJSON);

Upvotes: 1

Related Questions