aadu
aadu

Reputation: 3254

How to extract keys from key/value JSON object?

I'm being given some JSON I need to cycle through to output the elements. The problem is this section of it is structured differently. Normally I would just loop through the elements like this:

var json = $.parseJSON(data);
json[16].events.burstevents[i]

But I can't do that with the JSON below because they're key value pairs. How do I extract just the unix timestamp from the JSON below? (i.e. 1369353600000.0, 1371600000000.0, etc.)

{"16": {
    "events": {
      "burstevents": {
          "1369353600000.0": "maj", "1371600000000.0": "maj", "1373414400000.0": "maj", "1373500800000.0": "maj", "1373673600000.0": "maj"
        }, 
      "sentevents": {
          "1370736000000.0": "pos", "1370822400000.0": "pos", "1370908800000.0": "pos"
        }
     }
  }
}

Upvotes: 7

Views: 37064

Answers (3)

Tirthankar
Tirthankar

Reputation: 11

As an alternative we can do this:

var keys=[];
        var i=0;
        $.each(json, function(key, value) {
                console.log(key, value);
                keys[i++]=key;
        });

or maybe nest another .each for more set of key, value pairs.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

Try this

for(key in json["16"].events.burstevents)
{
    console.log(json["16"].events.burstevents[key]);
}

Demo: http://jsfiddle.net/qfMLT/

Upvotes: 2

Reactgular
Reactgular

Reputation: 54751

You can iterate over the keys using the in keyword.

var json = $.parseJSON(data);
var keys = array();
for(var key in json[16].events.burstevents)
{
    keys.push(key);
}

You can do it with jQuery

var json = $.parseJSON(data);
var keys = $.map(json[16].events.burstevents,function(v,k) { return k; });

You can use JavaScript Object

var json = $.parseJSON(data);
var keys = Object.keys(json[16].events.burstevents);

Upvotes: 11

Related Questions