javascript 事先不知道属性名称时如何解析JSON数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9728195/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:38:13  来源:igfitidea点击:

How to parse JSON data when the property name is not known in advance?

javascriptjsonproperties

提问by David Willis

Here is my response code in jQuery:

这是我在 jQuery 中的响应代码:

var response = $.parseJSON(response);

for (var i = 0; i < response.groupIds.length; i++) {
    console.log(response.groupIds[i], i);
}

Each response.groupIds[i]is of the form {"unknown name":"unknown value"}.

每个response.groupIds[i]都是形式{"unknown name":"unknown value"}

I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown nameis?

我希望在 javascript 中访问这两个数据位,如果我事先不知道 egunknown name是什么,我该如何实现?

回答by Rob W

Use Object.keysto retrieve a full list (array) of key names. A polyfill is available here.

使用Object.keys检索键名的完整列表(阵列)。一个 polyfill在这里可用。

var group = response.groupIds[i];

var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
    var name = allPropertyNames[j];
    var value = group[name];
    // Do something
}

Your question's response format contains only one key-value pair. The code can then be reduced to:

您问题的响应格式仅包含一个键值对。然后可以将代码简化为:

var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list;  = key name
var value = group[name];

If you're not interested in the list, use a for-i-inloop withhasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.

如果你没有在列表中感兴趣的话,使用for-i-in循环使用hasOwnProperty。必须使用最后一个方法,以排除从原型继承的属性。

for (var name in group) {
    if (group.hasOwnProperty(name)) {
        var value = group[name];
        // Do something
    }
}

回答by Niet the Dark Absol

Use a for..inloop:

使用for..in循环:

for( x in response.groupIds[i]) {
    // x is now your unknown key
    // response.groupIds[i][x] is the unknown value
}

Since there is only one property of the object, that'll work nicely.

由于对象只有一个属性,所以这会很好地工作。