JavaScript - 我正在读取json文件并尝试读取某个键的值

时间:2018-03-25 17:06:13

标签: javascript json

所以这是我的javascript代码,我循环遍历下面的json文件,我想检查嵌套在'相关'下的'buy_together'值,但我似乎无法使用我的代码我到目前为止。我正在使用'document.body.innerHTML ='hello';'所以我可以看看我的if语句是否有效,所以我可以执行我想做的事情。如果它不让我知道,希望这对你有意义。

$(function() {
  $.getJSON('test.json', function(data) {
    $.each(data.products, function(key, val) {
      for (var i = 0; i < data.products.length; i++) {
        var obj = data.products[i];
        if (obj.related == 'bought_together') {
          document.body.innerHTML = 'hello';
        }
      }

    });
  })
})

这是我的json文件的片段,以便您可以了解我正在使用的内容。

{
  "products": [{
    "asin": "B0001MQ60A",
    "title": "KEEN Men's Newport H2 Sandal",
    "imUrl": "http://ecx.images- 
    amazon.com / images / I / 41 pRaO7fFSL._SX395_.jpg ",
    "related": {
      "also_bought": ["B000MN8OR6"],
      "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4",
        "B003Z4KHXS", "B00GUBOCGQ",
        "B003O2SLXY", "B0017KSRMA", "B003O2SBKM", "B00DSN637U", "B000HDJ8IK", "B00E0J3HVG", "B003Z4KGZW",
        "B005HO2CYG", "B003H4QFVY", "B0017LB2VC", "B002R8JPTK", "B008KI84SE", "B005DJDL9A", "B003TU14OE",
        "B00E0J3HTI", "B000EDTVYY", "B003Z4JOJG", "B00DSN638E", "B00E0J3HVQ", "B008KI88JY", "B00EZIRE20",
        "B0095RGEH2", "B00CEX6MSU", "B000B84URK", "B003O2SPMG", "B002KKCWP4", "B003O2SLXE", "B00JQHFV0M",
        "B008JE8V14", "B0055ATVDW", "B003Z4KLMA", "B008ZAY40Y", "B003H4QFV4", "B00DSN64BU", "B002KKCZLA",
        "B0055ATVV4", "B00HFY47JY", "B00DPHJUTW", "B008FWRJ6I", "B003Z4JUFO", "B00JFB4RL8", "B00HR1LTNM",
        "B005HMTPBG", "B00KCT84I4", "B00HXDITEG"
      ],
      "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]
    },
    "salesRank": {
      "Shoes": 18
    },
    "categories": [
      ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],
      ["Clothing, Shoes & Jewelry", "K", "Keen"],
      ["Clothing, Shoes & Jewelry", "Comfort Shoes"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]
    ]
  }]
}

4 个答案:

答案 0 :(得分:1)

obj.related不包含字符串,它包含一个对象 - 所以你不想检查字符串“buy_together”,你想检查具有该名称的密钥是否存在:

// For demo, data is in a var instead of an ajax call:
var data = {
  "products": [{
    "asin": "B0001MQ60A",
    "title": "KEEN Men's Newport H2 Sandal",
    "imUrl": "http://ecx.images-amazon.com/images/I/41pRaO7fFSL._SX395_.jpg",
    "related": {
      "also_bought": ["B000MN8OR6"],
      "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4",
        "B003Z4KHXS", "B00GUBOCGQ",
        "B003O2SLXY", "B0017KSRMA", "B003O2SBKM", "B00DSN637U", "B000HDJ8IK", "B00E0J3HVG", "B003Z4KGZW",
        "B005HO2CYG", "B003H4QFVY", "B0017LB2VC", "B002R8JPTK", "B008KI84SE", "B005DJDL9A", "B003TU14OE",
        "B00E0J3HTI", "B000EDTVYY", "B003Z4JOJG", "B00DSN638E", "B00E0J3HVQ", "B008KI88JY", "B00EZIRE20",
        "B0095RGEH2", "B00CEX6MSU", "B000B84URK", "B003O2SPMG", "B002KKCWP4", "B003O2SLXE", "B00JQHFV0M",
        "B008JE8V14", "B0055ATVDW", "B003Z4KLMA", "B008ZAY40Y", "B003H4QFV4", "B00DSN64BU", "B002KKCZLA",
        "B0055ATVV4", "B00HFY47JY", "B00DPHJUTW", "B008FWRJ6I", "B003Z4JUFO", "B00JFB4RL8", "B00HR1LTNM",
        "B005HMTPBG", "B00KCT84I4", "B00HXDITEG"
      ],
      "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]
    },
    "salesRank": {
      "Shoes": 18
    },
    "categories": [
      ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],
      ["Clothing, Shoes & Jewelry", "K", "Keen"],
      ["Clothing, Shoes & Jewelry", "Comfort Shoes"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],
      ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]
    ]
  }]
}



// as noted in another answer, you can use $.each or a for loop, no need for both.
for (var i = 0; i < data.products.length; i++) {
  var obj = data.products[i];
  if (obj.related["bought_together"]) {
    console.log("found: ", obj.related["bought_together"]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

您不需要for循环,因为您已经完成了$.each循环

$(function() {

    $.getJSON('test.json', function(data) {
      $.each( data.products, function( key, val ) {
        if (Object.key(data.products.related).length) { // make sure the key related exist
            if (data.products.related['bought_together']) { 
               document.body.innerHTML = 'hello';
            }
        }
    });
    })})

如果您想使用for循环,请不要将其放入$.each

...

    for (var i = 0; i < data.products.length; i++) {
        var obj = data.products[i];

        if (obj.related['bought_together']) { // if doesn't exist return undefined
             document.body.innerHTML = 'hello';
        }

    }

答案 2 :(得分:0)

data.products[i].related是一个数组而不是字符串,因此要检查它是否存在,您可以使用

typeof data.products[i].related !== "undefined"

或者如果它总是存在,你需要知道它是否包含任何元素:

data.products[i].related.length>0

答案 3 :(得分:0)

如果我理解你,你想检查&#34; buy_together&#34;属性存在,如果是,则键入&#34; hello&#34;在你的文件中。

您可以更轻松地执行此操作,如下所示:

&#13;
&#13;
var jsonText = '{ "products": ['+
'{'+
'"asin": "B0001MQ60A",'+
'"title": "KEEN Men\'s Newport H2 Sandal",'+
'"imUrl": "http://ecx.images- amazon.com/images/I/41pRaO7fFSL._SX395_.jpg",'+
'"related": {'+
'  "also_bought": ["B000MN8OR6"],'+
'  "also_viewed": ["B0000DYKET", "B0035FE60M", "B008KI85R4", "B000MQWVA4"],'+
'  "bought_together": ["B003O2SLXY", "B003H4QFVY", "B002R8JPTK", "B000EDTVYY"]'+
'},'+
'"salesRank": {"Shoes": 18},'+
'"categories": ['+
' ["Clothing, Shoes & Jewelry", "Shoes & Accessories: International Shipping Available"],'+
' ["Clothing, Shoes & Jewelry", "K", "Keen"], ["Clothing, Shoes & Jewelry", "Comfort Shoes"],'+
' ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Sandals"],'+
' ["Clothing, Shoes & Jewelry", "Men", "Shoes", "Athletic", "Sport Sandals"]'+
']}'+
']}';

jsonObj = JSON.parse(jsonText);

var found = jsonObj.products.find(product => product.related && !!product.related["bought_together"]);

if (found) {
	document.body.innerHTML = 'hello';
}
&#13;
&#13;
&#13;