如何使用getJSON从json文件中获取数据

时间:2016-10-24 20:21:05

标签: jquery

我从外部JSON文件中获取数据。我想从文件中获取位置,但输出为“未定义”。任何人都可以帮我这个吗?

JQuery的

$(document).ready(function () {
   $.getJSON('data.json', function (data) {
      var output = "<ul class='search'>";
      $.each(data, function (key, value) {
           output += '<li>';
           output += '<h2>' + value.location + '</h2>';
           output += '</li>';
      });
      output += "<ul/>";
      $('#update').html(output);
   })
});

JSON

"data": [{
    "slug": "allsopp-allsopp",
    "id": 401,
    "imageToken": "d045e18526f988cceb63b08e71180fb6595d9f27",
    "name": "Allsopp & Allsopp",
    "location": "Dubai",
    "description": "Allsopp & Allsopp is a family founded property services company operating a traditional UK estate agency model in the United Arab Emirates (UAE). Our mandate is to deliver levels of customer care well above prevailing industry benchmarks, in a rapid and result oriented fashion which adheres strictly to the regulatory framework now governing the local property market. Consequently the staff we employ are expected to follow a business methodology which demands exceptional honesty, a stringent code of business conduct and total transparency to the client. The key objective at Allsopp & Allsopp is to be an all embracing property service centre that caters to all types of property related transactions in the UAE.",
    "residentialForRentCount": 521,
    "residentialForSaleCount": 1114,
    "commercialForRentCount": 1,
    "commercialForSaleCount": 0,
    "commercialTotalCount": 1,
    "totalProperties": 1636,
    "agentCount": 57,
    "licenseLabel": "RERA",
    "licenseNumber": "1815",
    "phone": "+971 4 429 4444",
    "links": {
        "self": "/en/broker/allsopp-allsopp-401",
        "logo": "https://www.propertyfinder.ae/images/pf_broker/logo/d045e18526f988cceb63b08e71180fb6595d9f27/desktop",
        "logo2x": "https://www.propertyfinder.ae/images/pf_broker/logo/d045e18526f988cceb63b08e71180fb6595d9f27/desktop2x"
    }
}

HTML

<div id="searcharea"></div>
<div id="update"></div>

1 个答案:

答案 0 :(得分:1)

#1 - 检查您的JSON是否有效JSONLint

(事实并非如此)。您需要在{之前的文件开头添加额外的"data": [{,并在末尾添加]}

#2 - 调试或使用console.log来了解您正在阅读的内容

key功能中打印value$.each,以便了解您正在阅读的内容。

#3 - 检查value是什么,如果确实存在value.location

您需要links财产的额外预防措施。 主对象的这个属性是另一个对象本身,具有自己的属性,它不像其他键那样是字符串或数字。