Omri Omri - 5 months ago 5
JSON Question

json parsing in JavaScript issue

I have the following json:

{
"result":[
{
"a": 500000,
"b": null,
"c": 0,
"d": 0,
"e": 1855
},
{
"a": 500001,
"b": null,
"c": 0,
"d": 0,
"e": 3770
}
],
"host": "43252ed565f9",
"time": "Wed Mar 23 09:57:43 UTC 2016",
"status": "Ok"
}


I'm trying to parse it, but got a strange value of
"["
, instead each one of the keys.

function f() {
var request1 = $.ajax({
url: '/a',
type: 'GET',
});
var request2 = $.ajax({
url : '/b',
type: "GET"
});
$.when(request1, request2).done(function(result1, result2){
//result1 = [Object, "success", Object]
json = JSON.stringify(result1)

for( key in json){
myJson = json[key] //The value is: "["

a = myJson['a']
b = myJson['b']
c = myJson['c']
d = myJson['d']
e = myJson['e']

}
})
}


What could be the issue?

Answer

No need to parse by JSON.parse() because the anwser is already a object.

function f() {
              var request1 = $.ajax({
                  url: '/a', 
                  type: 'GET',
              });
              var request2 = $.ajax({
                   url : '/b',
                   type: "GET"
              });
              $.when(request1, request2).done(function(result1, result2){
                        //result1 = [Object, "success", Object]


              for( key in result1){
                    a = result1[key] //The value is: "["

              }
})
          }

In fact ill show a snippet:

var Json = {
  "result": [{
    "a": 500000,
    "b": null,
    "c": 0,
    "d": 0,
    "e": 1855
  }, {
    "a": 500001,
    "b": null,
    "c": 0,
    "d": 0,
    "e": 3770
  }],
  "host": "43252ed565f9",
  "time": "Wed Mar 23 09:57:43 UTC 2016",
  "status": "Ok"
}

for (key in Json) {
  a = Json[key] //The value is: "["

}
document.getElementById("result").innerHTML = a
<p id="result"></p>

Reason Behind This

The reason behind this is because the JSON is already an object. Therfore there is no need to JSON.parse() it or JSON.stringify() it. Simple as that! Hope this helped!

FOR LOOP

In the for loop im looping over the objects.. And constantly rewritting the variable a. So at the end the variable a would equal "Ok", because thats the last "Object" in the JSON. Now lets say you want to keep every "Objects", then you will need a "count":

count=0; //GLOBAL VARIABLE.
  for ( key in result1){
    actualJSON[count]
    count++;
  }  

Now the actualJSON Has the all of the "objects" of that JSON.