Javascript中的JSON响应解析以获取键/值对[duplicate]

时间:2022-08-23 08:19:02

Possible Duplicate:
I have a nested data structure /how can I access a specific value?

可能的重复:我有一个嵌套的数据结构/我如何访问一个特定的值?

How can I get the name and value of each object in Javascript only?

如何只在Javascript中获取每个对象的名称和值?

4 个解决方案

#1


96  

There are two ways to access properties of objects:

访问对象属性有两种方式:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

或者,如果你需要动态地做:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

如果您还没有将其作为对象,那么需要对其进行转换。

For a more complex example, let's assume you have an array of objects that represent users:

对于更复杂的示例,让我们假设您有一个表示用户的对象数组:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

要访问第二个用户的年龄属性,您将使用用户[1].age。要访问第一个用户的第二个“favoriteFood”,你需要使用用户[0]. favoritefoods[2]。

Another example: obj[2].key[3]["some key"]

另一个例子:obj[2]。关键[3](“关键”)

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.

这将访问名为2的数组的第3个元素。然后,它将访问该数组中的“key”,进入该数组的第三个元素,然后访问属性名some key。


As Amadan noted, it might be worth also discussing how to loop over different structures.

正如Amadan所指出的,还应该讨论如何在不同的结构上循环。

To loop over an array, you can use a simple for loop:

要对数组进行循环,可以使用简单的for循环:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

对对象进行循环会稍微复杂一点。在对象是普通对象的情况下,可以使用plain for(在obj中为x){}循环,但是添加hasOwnProperty检查要安全得多。在无法验证对象没有继承属性的情况下,这是必需的。(它还对代码进行了一些将来的证明。)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

注意,我假设您使用的任何JS实现都有console.log。如果不是,您可以使用alert或某种DOM操作。

#2


10  

Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:

请尝试github上Douglas Crockford的JSON解析器。然后,您可以从字符串变量中创建一个JSON对象,如下所示:

var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'

var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];

#3


6  

Ok, here is the JS code:

这是JS代码:

var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')

for (var event in data) {
    var dataCopy = data[event];
    for (data in dataCopy) {
        var mainData = dataCopy[data];
        for (key in mainData) {
            if (key.match(/name|value/)) {
                alert('key : ' + key + ':: value : ' + mainData[key])
            }
        }
    }
}​

FIDDLE HERE

小提琴在这里

#4


4  

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • 首先,要有条理
  • top level reference must be a more convenient name other that a..v... etc
  • *的引用必须是一个更方便的名字,除了……等
  • in o.v,o.i.e no need for the array [] because it is one json entry
  • o.v o.i。不需要数组[],因为它是一个json条目

my solution

我的解决方案

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

通过代码

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

结果

*You should use distinguish accessorizes when using [] method or dot notation

*使用[]方法或点符号时,应使用区分装饰

Javascript中的JSON响应解析以获取键/值对[duplicate]

#1


96  

There are two ways to access properties of objects:

访问对象属性有两种方式:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

或者,如果你需要动态地做:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

如果您还没有将其作为对象,那么需要对其进行转换。

For a more complex example, let's assume you have an array of objects that represent users:

对于更复杂的示例,让我们假设您有一个表示用户的对象数组:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

要访问第二个用户的年龄属性,您将使用用户[1].age。要访问第一个用户的第二个“favoriteFood”,你需要使用用户[0]. favoritefoods[2]。

Another example: obj[2].key[3]["some key"]

另一个例子:obj[2]。关键[3](“关键”)

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.

这将访问名为2的数组的第3个元素。然后,它将访问该数组中的“key”,进入该数组的第三个元素,然后访问属性名some key。


As Amadan noted, it might be worth also discussing how to loop over different structures.

正如Amadan所指出的,还应该讨论如何在不同的结构上循环。

To loop over an array, you can use a simple for loop:

要对数组进行循环,可以使用简单的for循环:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

对对象进行循环会稍微复杂一点。在对象是普通对象的情况下,可以使用plain for(在obj中为x){}循环,但是添加hasOwnProperty检查要安全得多。在无法验证对象没有继承属性的情况下,这是必需的。(它还对代码进行了一些将来的证明。)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

注意,我假设您使用的任何JS实现都有console.log。如果不是,您可以使用alert或某种DOM操作。

#2


10  

Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:

请尝试github上Douglas Crockford的JSON解析器。然后,您可以从字符串变量中创建一个JSON对象,如下所示:

var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'

var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];

#3


6  

Ok, here is the JS code:

这是JS代码:

var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')

for (var event in data) {
    var dataCopy = data[event];
    for (data in dataCopy) {
        var mainData = dataCopy[data];
        for (key in mainData) {
            if (key.match(/name|value/)) {
                alert('key : ' + key + ':: value : ' + mainData[key])
            }
        }
    }
}​

FIDDLE HERE

小提琴在这里

#4


4  

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • 首先,要有条理
  • top level reference must be a more convenient name other that a..v... etc
  • *的引用必须是一个更方便的名字,除了……等
  • in o.v,o.i.e no need for the array [] because it is one json entry
  • o.v o.i。不需要数组[],因为它是一个json条目

my solution

我的解决方案

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

通过代码

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

结果

*You should use distinguish accessorizes when using [] method or dot notation

*使用[]方法或点符号时,应使用区分装饰

Javascript中的JSON响应解析以获取键/值对[duplicate]