davidjwest
davidjwest

Reputation: 546

How to reference JSON?

I have the following code:

$.getJSON('data.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<option id="' + key + '">' + val + '</option>');
  });

  $('<select/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This works fine for a simple JSON file but I've got a bit more complicated data (this is how it's been given to me):

{
   "Shares": [
   {
      "shareName": "Frontier",
      "shareID": "FML"
   },
   {
      "shareName": "Global Petroleum",
      "shareID": "GBP"
   },
   {
      "shareName": "Tower Petroleum",
      "shareID": "TRP"
   },
   {
      "shareName": "Aquarius Platinum",
      "shareID": "AQP"
   }
   ]
}

This simply populates a drop down menu, how should I modify the syntax so it reads the "ShareName" for each within Shares?

Thanks!

Thanks everyone for the answers, I can only choose one so chose the first reply, but I really appreciate everybody's input!

Upvotes: 0

Views: 270

Answers (4)

Alnitak
Alnitak

Reputation: 340055

Iterate over data.Shares, but I suggest creating the <option> elements directly instead of by concatenating HTML to ensure that any meta-characters are correctly escaped:

$select = $('<select/>', {
    'class': 'my-new-list',
});

$.each(data.Shares, function(index, val) {
    $('<option>', {
       id: val.shareID, val: val.shareID, text: val.shareName
    }).appendTo($select);
});

$select.appendTo('body');

Note that I've also put the share ID into the <option> value, so that you can use that abbreviated token in the backend instead of the full share name.

Upvotes: 1

Ehtesham
Ehtesham

Reputation: 2985

    $.each(data.Shares, function(val) {
         items.push('<option id="' + val.ShareId+ '">' + val.ShareName+ '</option>');
    });

Upvotes: 0

Femaref
Femaref

Reputation: 61497

After parsing, it is a javascript object, so instead of iterating over an array, iterate over the array named by the Shares field:

$.each(data.Shares, function(key, val) {
  items.push('<option id="' + val.shareID + '">' + val.shareName + '</option>');
});

Upvotes: 0

Matt
Matt

Reputation: 75327

Firstly, you'll have to iterate over data.Shares instead. Note the capital S; JavaScript is case sensitive.

You'll also have to reference the shareName and shareID attributes rather than simply the key and value.

  $.each(data.Shares, function(_, val) {
    items.push('<option id="' + val.shareID + '">' + val.shareName + '</option>');
  });

To cement the understanding, what you have is an object (data) which has an attribute (Shares) which is an array of objects. Each object in that array has 2 attributes; shareID and shareName.

Upvotes: 1

Related Questions