Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
        }
     }
  }
}
like image 414
aadu Avatar asked Aug 06 '13 12:08

aadu


People also ask

How do you get keys from objects in Mule 4?

You can use the pluck function to get an Array of all the Keys from the Object. Note that this will return an Array of Keys and not an Array of Strings.

Can a JSON object be a key?

Since JSON can only be contained in strings in JS, you can use JSON as key. E.g. var obj = {'{"foo": 42}': "bar"}; . If you mean a JS object, no, that's not possible. You can use objects as keys, but they're converted into strings.


1 Answers

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);
like image 69
Reactgular Avatar answered Oct 18 '22 01:10

Reactgular