How to extract keys from a JSON object with key / value?

I am given some JSON I need to iterate over the elements for output. The problem is that this section is structured differently. Usually I just scrolled through the following elements:

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

But I can not do this with JSON below, because these are key value pairs. How can I extract only unix timestamp from 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" } } } } 
+6
source share
3 answers

You can iterate over 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); 
+9
source

try it

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

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

+1
source

Alternatively, we can do this:

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

or, possibly, a different .each for more key pairs, values.

+1
source

Source: https://habr.com/ru/post/951124/


All Articles