0

I have a json which is like

{
"Payload":[{
    "PrevYr":"21333",
    "CurYr":"123454"
},{
    "PrevYr":"234333",
    "CurYr":"45546"
},{
    "PrevYr":"3563",
    "CurYr":"67854"
}]
}

Now in my code i read this json using

  $.getJSON("readJson.json", function (data) {}

I need to read the json and create another json with some changes on it. But i can't read the "CurYr" and "PrevYr". I mean not their values. But them. So if there is 2014 and 2015 in place of curyr and prevyr i can get them also. I need to read the left side. Please help..

Vanarajan
  • 973
  • 1
  • 10
  • 35
Subho
  • 921
  • 5
  • 25
  • 48

3 Answers3

1

Try something like this,

    var test = {
"Payload":[{
    "PrevYr":"21333",
    "CurYr":"123454"
},{
    "PrevYr":"234333",
    "CurYr":"45546"
},{
    "PrevYr":"3563",
    "CurYr":"67854"
}]};

$.each(test.Payload,function(key,val){
        $.each(val,function(key1,val1){
        alert(key1);
    }); 
});

or

var keySet = Object.keys( test.Payload[0] );
 alert( keySet[0]);
 alert( keySet[1]);
0

you can use Object.keys( obj );

try

$.getJSON("readJson.json", function (data) {

 console.log( Object.keys(data.Payload[0]));

}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

try this:

var obj = {
"Payload":[{
    "PrevYr":"21333",
    "CurYr":"123454"
},{
    "PrevYr":"234333",
    "CurYr":"45546"
},{
    "PrevYr":"3563",
    "CurYr":"67854"
}]
}

var objKeys = Object.keys(obj);

objKeys.forEach(function(key){
  // This returns "Payload"
  var _innerKeys = Object.keys(obj[key]);
  
  // This returns "0,1,2" since obj[key] is an array.
  _innerKeys.forEach(function(k){
    
    // This will return "PrevYr, CurYr"
    var _innerProp = Object.keys(obj[key][k]);
    console.log(_innerProp);
  })
  console.log("Inner Keys: ", _innerKeys);
})
Rajesh
  • 24,354
  • 5
  • 48
  • 79