循环通过JSON文件

时间:2017-03-20 20:56:19

标签: json loops iteration

正如标题所示我试图读取如下所示的JSON文件:

{
    "response": {
        "current_time": 1490040712, 
        "success": 1, 
        "items": {
            "AK-47 | Black Laminate (Minimal Wear)": {
                "last_updated": 1490025658, 
                "value": 985, 
                "quantity": 124
            }, 
            "AK-47 | Aquamarine Revenge (Field-Tested)": {
                "last_updated": 1490025658, 
                "value": 1775, 
                "quantity": 127
            }, 
            "AK-47 | Black Laminate (Field-Tested)": {
                "last_updated": 1490025658, 
                "value": 890, 
                "quantity": 130
            }, 
            "AK-47 | Aquamarine Revenge (Battle-Scarred)": {
                "last_updated": 1490025658, 
                "value": 1202, 
                "quantity": 70
            }, 
        }
    }
}

现在我要做的就是遍历JSON文件并检查是否,例如" AK-47 |海蓝宝石复仇(战痕累累)"与给定的字符串相同,然后返回它的值。我试着在互联网上看一看这样做的好看但是我并没有真正变得更聪明,我尝试了一些方法,但他们并没有那么顺利。

我试过的东西:

    var d, i;
    for (i = 0; i < prices.response.items.length; i++) {
        //d = prices.response.data[i];
        itemPrice = i;
    }

这篇文章只是为了测试而至少返回一些东西,但它根本不起作用,有人可以帮助我吗?

亲切的问候!

1 个答案:

答案 0 :(得分:0)

这是您检查单个值的方法:

var json =  {"response":
{"success":1,
"current_time":1490040712,
"items":
  {"AK-47 | Aquamarine Revenge (Battle-Scarred)": {"last_updated":1490025658,"quantity":70,"value":1202},
 "AK-47 | Aquamarine Revenge (Factory New)":{"last_updated":1490025658,"quantity":46,"value":3465},
 "AK-47 | Aquamarine Revenge (Field-Tested)":{"last_updated":1490025658,"quantity":127,"value":1775},
 "AK-47 | Aquamarine Revenge (Minimal Wear)":{"last_updated":1490025658,"quantity":92,"value":2427},
 "AK-47 | Aquamarine Revenge (Well-Worn)":{"last_updated":1490025658,"quantity":87,"value":1527},
 "AK-47 | Black Laminate (Battle-Scarred)":{"last_updated":1490025658,"quantity":45,"value":955},
 "AK-47 | Black Laminate (Factory New)":{"last_updated":1490025658,"quantity":11,"value":10152},
 "AK-47 | Black Laminate (Field-Tested)":{"last_updated":1490025658,"quantity":130,"value":890},
 "AK-47 | Black Laminate (Minimal Wear)":{"last_updated":1490025658,"quantity":124,"value":985}}
 }
};

alert(json.response.items["AK-47 | Aquamarine Revenge (Battle-Scarred)"].value);

由于项目不是列表,而是对象,因此我们不能简单地遍历它。 你只需要像使用一样迭代它们 这是获得属性数量的方式:

 Object.getOwnPropertyNames(json.response.items).length

参见参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

这里有一个代码示例,说明如何遍历链接上的键和值。

 Object.getOwnPropertyNames(json.response.items).forEach(
   function (val, idx, array) {
    console.log(val + ' -> ' + obj[val]);
   }
 );