JK.Lin JK.Lin - 3 months ago 12
JSON Question

With use JSON.parse(), how to take value in multi dimensional array?

Before use JSON.parse, an JSON array is shown below:

var temp = {
"queries": [
{
"sample_size": 3,
"results": [
{
"name": "temperature",
"tags": {
"Tag": [
"temperature"
]
},
"values": [
[
1452221580000,
27.5
],
[
1452221640000,
27.1
],
[
1452221700000,
27.3
]
]
]}
]}
}


I need to get the value from the array, so I use JSON.parse().

var jsonparse_temp = JSON.parse(temp);
var dataNum = jsonparse_temp ['queries']['sample_size'];
var timestamp1 = jsonparse_temp ['queries']['results']['value'][0][0]
var value1 = jsonparse_temp ['queries']['results']['value'][0][1]


After that, is
value1
equal
27.5
?
I'm not sure this way could sign the value to variable.

Answer

It's not a JSON string it's a well-formed object no need to parse it. There is nested array so you need to get the object element from the array using the index.

var temp = {
  "queries": [{
    "sample_size": 3,
    "results": [{
      "name": "temperature",
      "tags": {
        "Tag": [
          "temperature"
        ]
      },
      "values": [
        [
          1452221580000,
          27.5
        ],
        [
          1452221640000,
          27.1
        ],
        [
          1452221700000,
          27.3
        ]
      ]
    }]
  }]

};

// using bracket notation
var dataNum = temp['queries'][0]['sample_size'];
var timestamp1 = temp['queries'][0]['results'][0]['values'][0][0]
var value1 = temp['queries'][0]['results'][0]['values'][0][1];

console.log(dataNum, timestamp1, value1);

// using dot notation
var dataNum1 = temp.queries[0].sample_size;
var timestamp11 = temp.queries[0].results[0].values[0][0]
var value11 = temp.queries[0].results[0].values[0][1];


console.log(dataNum1, timestamp11, value11);

Comments