jQuery 如何从键/值 JSON 对象中提取键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18080543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract keys from key/value JSON object?
提问by AzzyDude
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"
}
}
}
}
回答by Reactgular
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 对象
var json = $.parseJSON(data);
var keys = Object.keys(json[16].events.burstevents);
回答by Satpal
Try this
尝试这个
for(key in json["16"].events.burstevents)
{
console.log(json["16"].events.burstevents[key]);
}
回答by Tirthankar
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
以获得更多的键值对。