0

I'm very new to using JSON with AJAX so I'm not sure what I'm doing wrong. I've looked up various examples, but can't seem to pull the JSON data correctly. I believe it's how my JSON file is set up. I've tried with other examples and got it to work, but the way mine is written is different. Can anyone help me? I need to be able to output the data from the JSON object.

My JSON looks like this:

[
   {
      "ID": 512,
      "FirstName":"John",
      "LastName":"Smith",
      "Age":26,
      "Email":"johnsmith@gmail.com",
      "Phone1":"555-555-5555",      
   },
   {
      "ID": 513,
      "FirstName":"Jane",
      "LastName":"Smith",
      "Age":24,
      "Email":"janesmith@gmail.com",
      "Phone1":"555-555-5555",      
   },
]   

My script is below:

$.getJSON("test.json", function (data) {
    $.each(data, function (index, value) {
        var items = [];

        $("div").append(items);
    });
});

I'm not sure how get the values inside the JSON object for my variable of items. Any help would be greatly appreciated!

user933061
  • 13
  • 1
  • 8
  • In your `$.each` loop, `value` will be an object (each value in the array). `value.ID` will be the ID, etc. – gen_Eric Jun 02 '16 at 21:30
  • 1
    You append "items" to the div but never add any items to the "items" array. – PFlans Jun 02 '16 at 21:31
  • Please consider learning about the debugging tools in your browser. Most browsers allow you to press F12 to access them. [Here's a basic one from Microsoft for their Edge browser](https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/f12-devtools-guide/). Similar techniques can be used in other browsers. With that knowledge, setting a breakpoint inside the `$.each` will tell you what's in the `value` variable. – Heretic Monkey Jun 02 '16 at 21:51

1 Answers1

0

First a bit of clarity: Once you get the data, you are no longer dealing with JSON. It has become a simple JavaScript array, and each element of the array is a JavaScript Object.

var data = [{
  "ID": 512,
  "FirstName": "John",
  "LastName": "Smith",
  "Age": 26,
  "Email": "johnsmith@gmail.com",
  "Phone1": "555-555-5555",
}, {
  "ID": 513,
  "FirstName": "Jane",
  "LastName": "Smith",
  "Age": 24,
  "Email": "janesmith@gmail.com",
  "Phone1": "555-555-5555",
}];

console.log(data[0]); // the first element
console.log(data[0].FirstName);

for (var i = 0; i < data.length; i++) {
  console.log(data[i].Age);
}
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • How would I retrieve the value of "FirstName" without specifying First.Name in the script? How do I loop through and get the values without having to specify? – user933061 Jun 02 '16 at 21:49