如何从键/值JSON对象中提取键?

时间:2022-12-02 16:04:25

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:

我正在获得一些JSON,我需要循环来输出元素。问题是它的这一部分结构不同。通常我会循环遍历这样的元素:

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.)

但我不能用下面的JSON做到这一点,因为它们是键值对。如何从下面的JSON中仅提取unix时间戳? (即1369353600000.0,1371600000000.0等)

{"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"
        }
     }
  }
}

3 个解决方案

#1


9  

You can iterate over the keys using the in keyword.

您可以使用in关键字迭代密钥。

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

You can do it with jQuery

你可以用jQuery做到这一点

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

You can use JavaScript Object

您可以使用JavaScript Object

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

#2


1  

Try this

尝试这个

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

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

演示:http://jsfiddle.net/qfMLT/

#3


1  

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.

或者可以嵌套另一个.each以获得更多的键值对。

#1


9  

You can iterate over the keys using the in keyword.

您可以使用in关键字迭代密钥。

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

You can do it with jQuery

你可以用jQuery做到这一点

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

You can use JavaScript Object

您可以使用JavaScript Object

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

#2


1  

Try this

尝试这个

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

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

演示:http://jsfiddle.net/qfMLT/

#3


1  

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.

或者可以嵌套另一个.each以获得更多的键值对。