如果事先不知道属性名称,如何解析JSON数据? [英] How to parse JSON data when the property name is not known in advance?

查看:114
本文介绍了如果事先不知道属性名称,如何解析JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is my response code in jQuery:

var response = $.parseJSON(response);

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

每个 response.groupIds [i] 的格式为 {未知名称:未知值}

我希望要在javascript中访问这两个数据位,如何在事先不知道什么的情况下完成此操作未知名称是?

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 name is?

推荐答案

使用 Object.keys 检索完整列表(数组)关键名称。可以使用此处获取polyfill。

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

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

如果您对列表不感兴趣,请使用 for -i -in 循环 hasOwnProperty 。必须使用最后一个方法来排除从原型继承的属性。

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

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

这篇关于如果事先不知道属性名称,如何解析JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆