简体   繁体   English

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

[英]How to extract keys from key/value JSON object?

I'm being given some JSON I need to cycle through to output the elements. 我正在给我一些JSON,我需要循环来输出元素。 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. 但我不能用下面的JSON做到这一点,因为它们是键值对。 How do I extract just the unix timestamp from the JSON below? 如何从下面的JSON中仅提取unix时间戳? (ie 1369353600000.0, 1371600000000.0, etc.) (即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"
        }
     }
  }
}

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

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/

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以获得更多的键值对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM