faizy faizy - 1 year ago 155
jQuery Question

How to fetch data from json file using getJSON

I am fetching data from external JSON file. I want to fetch location from the file, but there is an output of "undefined". Can anyone help me with this?


$(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/>";


"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"


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

Answer Source

#1 - Check if your JSON is valid JSONLint

(It's not). You need to add an extra { at the start of the file before "data": [{ and add ]} at the end

#2 - Debug or use console.log to know what you are reading

Print keyand value, inside the $.each function, so you can understand what you are reading.

#3 - Check what is value, and if does exist any value.location

You need extra precautions for links property. This property of the main object, is another Object itself, with his own properties, it is not a string or number like the others keys.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download