Sarah Sarah - 1 year ago 78
JSON Question

Accessing specific JSON values in HTML

I have an AJAX call like this that fetches a library of books:

$(function() {
$.getJSON($SCRIPT_ROOT + '/_bookCount',
function(data) {
$("#books").text(data.books);
});
});


This produces a JSON result like this, which counts each book according to genre:

{
"books": {
"mystery": 1,
"romance": 2,
"horror": 0,
"fantasy": 3,
"biography": 1
}
}


I want to display the specific counts for each genre in my HTML. This is what I have so far, but I know it's incorrect:

<p> <span id="books.mystery"></span> Mysteries<br>
<span id="books.romance"></span> Romances<br>
<span id="books.horror"></span> Horrors<br>
<span id="books.fantasy"></span> Fantasies<br>
<span id="books.biography"></span> Biographies </p>


This doesn't work/display anything obviously and I know it's probably a simple question, but I'm new to this and I don't know the right way to do it. How can I access specific values from this JSON result and put them in my HTML?

Answer Source

The way you are assigning data is completely wrong.

Try this:

$(function() {
  $.getJSON($SCRIPT_ROOT + '/_bookCount',
  function(data) {
    $.each(data.books, function(key, val) {
      $("#books\\." + key).text(val);
    }
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download