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

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

JSON response parsing in Javascript to get key/value pair

javascriptjsonparsing

提问by Parekh Shah

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

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

回答by Corbin

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

要访问第二个用户的年龄属性,您可以使用users[1].age. 要访问第一个用户的第二个“favoriteFood”,您需要使用users[0].favoriteFoods[2].

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

另一个例子: obj[2].key[3]["some key"]

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 的数组的第三个元素。然后,它将访问该数组中的 'key',转到该数组的第三个元素,然后访问属性 name 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 hasOwnPropertycheck. 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.)

遍历一个对象有点复杂。如果您绝对肯定对象是普通对象,则可以使用普通for (x in obj) { }循环,但添加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 alertor some kind of DOM manipulation instead.)

(请注意,我假设您使用的任何 JS 实现都具有console.log。如果没有,您可以使用alert或某种 DOM 操作来代替。)

回答by Sachin Sharma

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 Parser 。然后,您可以简单地从您的 String 变量中创建一个 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"];

回答by pala?н

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

在这里小提琴

回答by Rami Jamleh

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
  • 首先,组织起来是个好主意
  • 顶级引用必须是一个更方便的名称,除了 a..v... 等
  • 在 ov,oie 中不需要数组 [] 因为它是一个 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

*在使用 [] 方法或点表示法时,您应该使用区分附件

proove

证明