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"
}
}
}
}
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With