0

I'm trying to get API info using jQuery to affect an HTML tag. I'm able to do this, but only when text only is on the URL. (See code)

<script>
    $(document).ready(function() {
    $.get('https://garli.co.in/api/getdifficulty', function(difficulty) {
        $("#difficulty").text(difficulty);
    });
});
</script>
<p id="difficulty">Check Network Connection and Try Again</p>

What I'm trying to do is select specific JSON objects (a format that I'm not familiar with), in the style of what is below:

[
  {
    "name": "Joe",
    "last_name": "Smith", 
    "age": "37"
  }
]

How would I get just the "name" value? When I try to get any part of it, what I'm currently recieving is [object Object].

  • Well it is an array so how would you access the first item in an array? Than the first item is an object, how do you reference items in an object? – epascarello Feb 03 '18 at 01:11
  • 1
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Heretic Monkey Feb 03 '18 at 01:15

2 Answers2

0

You can use JSON.stringify to convert the object into a string that shows the contents and is not "[object Object]", or you can just get a property and show that. By the example you showed it would be for example: json[0].name where json is the object

[
  {
    "name": "Joe",
    "last_name": "Smith", 
    "age": "37"
  }
]
mdatsev
  • 3,054
  • 13
  • 28
0

If your .get() call is similar to that call in your question, you need to handle your response as follow:

Here your dataType = string, so your response will be a text.

$.get('URL', function(response) {
    $("#target").text(JSON.parse(response)[0].name);//here your response is parsed to JSON object.
}); 

If you want to avoid the parsing step, then execute .getJSON() as follow:

Here the response will be a JSON object.

$.getJSON('URL', function(response) {
    $("#target").text(response[0].name); // Your response was parsed to JSON object.
}, 'json');
Ele
  • 33,468
  • 7
  • 37
  • 75