Reading a JSON file using jQuery

Hi, I am trying to read data from a JSON file using jQuery. This is my JS:
$(document).ready(function() { var myItems; $.getJSON('testData.json', function(data) { myItems = data.items; console.log(myItems); }); }); 

And this is the JSON file:

 {"fname":"rafael","lname":"marques","age":"19"} {"fname":"daniel","lname":"marques","age":"19"} 

When I open my HTML page in a browser, I do not see anything in the console.

+9
json jquery
source share
2 answers

Add a comma after each object, then wrap it with [] and attach them to the object with the items property in the json file so that it looks like

 { items: [ { "fname": "rafael", "lname": "marques", "age": "19"}, { "fname": "daniel", "lname": "marques", "age": "19" }] } 

then you should try

 $.each(data.items, function(key, val) { alert(val.fname); alert(val.lname); }) 
+13
source share
 {"fname":"rafael","lname":"marques","age":"19"} {"fname":"daniel","lname":"marques","age":"19"} 

Invalid json file. Add a comma between the lines or do this:

 {items:[ {"fname":"rafael","lname":"marques","age":"19"}, {"fname":"daniel","lname":"marques","age":"19"} ]} 

to meet your obvious requirements.

But opening a console to look for errors would solve this problem.

+2
source share

All Articles