0

I am trying to work with an API to get JSON pulled from online, it keeps interpreting text as objects, if you compare the output this gives and the source of the link, it fails to grab some key information.

$(document).ready(function() {
  $.getJSON("http://www.dnd5eapi.co/api/races/1", function(result) {
    $.each(result, function(i, field) {
      $("#output").append(field + "</br> ");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div id="output"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    The reason is because the request returns JSON. You need to format that object as you require instead of simply coercing it to a string by appending it to an existing element. – Rory McCrossan Mar 29 '17 at 12:51
  • Could you point me towards somewhere I could read more on this topic? – Carl Nelson Mar 29 '17 at 12:55
  • For your reference, this is the full response: http://www.jsoneditoronline.org/?id=13d2afdcd0c51d3ce2c9c8a4778c6850 – Rory McCrossan Mar 29 '17 at 12:56

1 Answers1

0

It does not miss key information, you are simply iterating through the properties of the result JSON object. You are not iterating through the properties of the properties of the object, and so on, recursively. You can see some [object Object] in the output, these occur if a property value is another object instead of a string. These contain the information you are "missing".

As Rory McCrossan said, this is because you are gettin a JSON result and you get it already parsed in an object rather than a string. This way you can easily access its properties, but if you rather need the original string, use $.get or $.ajax instead of $.getJSON and specify the dataType as text.

For recursive JSON iteration, see this.

Example for simple text-based parsing:

$(document).ready(function(){
    $.get(
    {
        url: "http://www.dnd5eapi.co/api/races/1",
        dataType: "text",
        success: function(result){
            $("#output").append(result);
    }});
});
Community
  • 1
  • 1