0

I want to be able to output all these objects and it's contents from this JSON file on the webpage by a button. Please don't tell me to use console.log I'm not trying to do that I actually want to output this on a webpage and i'm clueless on how to do that. Ignore the section where I was trying to get a single content from an object. The JSON FILE

{
        "name": "Adam",
        "age": 21,
        "interest": ["food", "relaxing"]
    },

    {
        "name": "Bob",
        "age": 22,
        "interest": ["working out", "sleeping"]
    },

    {
        "name": "Cane",
        "age": 23,
        "interest": ["football", "vide games"]
    }

The AJAX file

<!DOCTYPE html>
<html>
<body>

<div id="demo">

<button type="button" onclick="x()">Change Content</button>
</div>

<script>
function x() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var employees = JSON.parse(xhr.responseText);
document.getElementById("demo").innerHTML =
employees.name;
}
};
xhr.open("GET", "json_example.json", true);
xhr.send();
}
</script>

</body>
</html>
  • 1
    For starters that isn't a valid structure. Is missing outside array quotes `[]`. Use an online json validator to validate your json – charlietfl Aug 07 '17 at 14:21

1 Answers1

-2

use a pre tag

HTML

<pre id="jsonText"></pre>

JS

document.getElementById("jsonText").innerHTML = JSON.stringify(employees, null, 2);

see https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/JSON/stringify for stringify documentation

  • This is not a duplicate this is situation based its not even close to a duplication. –  Aug 07 '17 at 14:37