2

I have the following JSON data:

{"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.368999999999999772626324556767940521240234375,"src":"us","eqid":"c0001xgp","magnitude":8.800000000000000710542735760100185871124267578125,"lat":38.3220000000000027284841053187847137451171875},{"datetime":"2012-04-11 06:38:37","depth":22.89999999999999857891452847979962825775146484375,"lng":93.06319999999999481588019989430904388427734375,"src":"us","eqid":"c000905e","magnitude":8.5999999999999996447286321199499070644378662109375,"lat":2.31099999999999994315658113919198513031005859375},{"datetime":"2007-09-12 09:10:26","depth":30,"lng":101.3815000000000026147972675971686840057373046875,"src":"us","eqid":"2007hear","magnitude":8.4000000000000003552713678800500929355621337890625,"lat":-4.51719999999999988204990586382336914539337158203125}]}

I'm trying to display some of the above data to the browser, but I get this showing in the browser instead.

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

My code is

var xmlhttp = new XMLHttpRequest();

      xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
          if (xmlhttp.status == 200) {
            const jsonResponse = JSON.parse(xmlhttp.responseText);
            for (response in jsonResponse)
            // console.log(jsonResponse[response])
            $('#result1').html(`${jsonResponse[response]}`);
          } else {
            alert('Problem in parsing JSON data via AJAX');
          }
        }
      };

When I console.log(jsonResponse[response]) I can see the array of data, but can't figure out how to get it to display on the browser properly.

Thank you in advance for any help.

  • Hey, welcome to Stack Overflow! Have you checked the answer to [this question](https://stackoverflow.com/questions/34864184/how-to-display-a-json-representation-and-not-object-object-on-the-screen)? JSON data is stringified to [object Object] when you surround it with backticks. If you still want to use backticks, consider this change: `JSON.stringify(jsonResponse[response])` – Nikolay Shebanov Nov 20 '20 at 20:44
  • Thank you for the warm welcome and I'll check out the link. –  Nov 21 '20 at 13:12

2 Answers2

0

The issue is you're passing an object in a string literal without stringifying the object $('#result1').html(`${jsonResponse[response]}`); should actually be $('#result1').html(`${JSON.stringify(jsonResponse[response])}`);.

Seth250
  • 16
  • 4
0

You can't display objects using html. Rather, you can convert the json to string and show using JSON.stringify and wrap it inside pre tag.

$('#result1').html(`<pre>${jsonResponse[response]}</pre>`)
mathu mitha
  • 306
  • 2
  • 6