0

I am using the example from:

Get JSON data from external URL and display it in a div as plain text

To get information from a JSON with nested data but I am getting the result:

[object Object]

How can I get the NAME or JOB information?

HTML

<div id="result" style="color:red"></div>

JavaScript

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) {
    alert('Your Json result is:  ' + data.queries); //you can comment this, i used it to debug

    result.innerText = data.queries; //display the result in an HTML element
}, function(status) { //error detection....
  alert('Something went wrong.');
});

JSON

{ 
  "queries":[ 
      { 
         "query":{ 
            "CODE":"555443567",
            "NAME":"NAME LASTNAME",
            "JOB":"JOB TITLE"
         }
      }
   ]
}
Rodrick
  • 595
  • 10
  • 27

3 Answers3

1

You cannot print an object as text in JavaScript. However, you convert the object to string and append it to the DOM. Instead of result.innerText = data.queries try result.innerText = JSON.stringify(data.queries). Do note the output string won't be formatted.

Pablo
  • 5,897
  • 7
  • 34
  • 51
  • Thanks. I got the JSON. How can I get just the NAME or JOB? – Rodrick Sep 23 '19 at 01:01
  • 1
    If you want to get specific data from the json response then you do not have to convert it to a string. You inspect the `data` in the browser console by using `console.log(data)`. Based on the example data you provided you can access the NAME and JOB respectively with `data.queries[0].query.NAME` and `data.queries[0].query.JOB` – Pablo Sep 23 '19 at 04:06
0

You can try a pure pipe javascript if you don't use any framework like Angular (which provides a JSON pipe).

For example, you can use this one: http://azimi.me/json-formatter-js/

Dody
  • 608
  • 7
  • 19
0

You won't be able to assign it directly as data.queries is an object. However, if we use something like JSON.stringify we can convert it to a string and use that in the UI instead.

Since you're wanting to print to the DOM, you might consider using a pre element instead of a div as that will allow for better formatting etc.

  • also note there are some additional params that will allow you to adjust the whitespace used etc.

Here's an answer to a similar question that is pretty awesome as it adds "syntax highlighting" to the displayed JSON as well.