简体   繁体   English

如何使用Javascript迭代返回的JSON字符串?

[英]How can I iterate through a returned JSON string using Javascript?

I have an API endpoint that returns some data in the below format. 我有一个API端点,以下面的格式返回一些数据。

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
}

I thought it would be relatively trivial to be able to iterate through each key-value pair in this JSON payload, but I seem to be having errors with it. 我认为能够遍历此JSON有效负载中的每个键值对会相对微不足道,但我似乎遇到了错误。 The code I have below is what I am using to first parse the JSON from string format into a variable, then I want to iterate through each key in the JSON object, retrieve the key and value, and then do something with both of those values. 下面的代码是我用来首先将JSON从字符串格式解析为变量,然后我想迭代JSON对象中的每个键,检索键和值,然后对这两个值执行某些操作。

var dictionary = JSON.parse(data);

for (var key in dictionary) {
    var identifier = key;
    var identifierValue = dictionary[key];

    //do stuff..

I'm not sure whether the for() is valid in this instance, how exactly can I iterate through each key-value pair in the JSON object? 我不确定for()在这个实例中是否有效,我怎样才能迭代JSON对象中的每个键值对?

My issue is that I can't seem to access they keys or values held in the dictionary variable. 我的问题是我似乎无法访问字典变量中保存的键或值。 It seems as though the for loop isn't working, which makes me feel like it's invalid for this use case. 似乎for循环不起作用,这让我觉得它对这个用例无效。 If this was C# I'd have to do something similar to 如果这是C#,我必须做类似的事情

for(var key in dictionary.keySet)
{
    //do...
}

I'm looking for the equivalent in JS. 我正在寻找JS中的等价物。

The code you posted looks oke, however there are alternative ways to iterate over an object: 您发布的代码看起来很棒,但是有其他方法来迭代对象:

Object.keys(jsonObject)
  .forEach(function eachKey(key) { 
    alert(key); // alerts key 
    alert(jsonObject[key]); // alerts value
  });

Your approach is just fine. 你的方法很好。 You iterate dictionary, it will store the key in var key . 您迭代字典,它将密钥存储在var key

To access the value of this iterated array, you just access the array with the key. 要访问此迭代数组的值,只需使用键访问该数组即可。

for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
         var value = dictionary[key]
         console.log(key + '=>' + value);
    }
}

Your own code seems alright. 你自己的代码似乎没问题。 No idea why it throws an error from the code shown. 不知道为什么它会从显示的代码中抛出错误。

The Object.entries() example I commented about goes as follows: 我评论过的Object.entries()示例如下:

 const data_json = '{"key1":"value1","key2":"value2","key3": "value3"}'; const dictionary = JSON.parse( data_json ); Object.entries( dictionary ).forEach(([ key, value ]) => { console.log( `found key ${ key } with value ${ value }` ); }); 

It seems you want to know some other ways of doing that. 看来你想知道其他一些方法。 There can be other ways 可以有其他方式

Object.entries and forEach() Object.entriesforEach()

 let obj = { "key1": "value1", "key2": "value2", "key3": "value3" } Object.entries(obj).forEach(([key, value]) => { console.log(key); console.log(value) }) 

Object.keys and forEach() Object.keysforEach()

 let obj = { "key1": "value1", "key2": "value2", "key3": "value3" } Object.keys(obj).forEach(key => { console.log(key); console.log(obj[key]) }) 

If your API data are surrounding by a quotation, then you need to use JSON.parse before run an iterator. 如果您的API数据周围有引号,那么您需要在运行迭代器之前使用JSON.parse

var data = '{"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"}';

var cars = JSON.parse(data);

Object.keys(cars).forEach(function(key) {
    console.log(key + "=" + cars[key]);
});

And if data are plain object, no need to use JSON.parse . 如果数据是普通对象,则无需使用JSON.parse

var cars = {"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"};

Object.keys(cars).forEach(function(key) {
    console.log(key + "=" + cars[key]);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM