I have trying to show the JSON data on the HTML page but weirdly it doesn't show the JSON data but shows this.
The same code works well if the inner.HTML line is removed and used console.log instead, this is the output if console.log is used instead of inner.HTML.
Code:
pat = $.getJSON("../data/random/anime/pat/pat.json");
function randomObject(obj) {
let arr = Object.values(obj);
content = arr[Math.floor(Math.random() * arr.length)];
document.getElementById("content").innerHTML = content;
}
randomObject(pat);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASEAN API V2</title>
</head>
<body>
<p id="content"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./scripts/api.js"></script>
</body>
</html>
The JSON data:
[
{
"gif": "https://media.discordapp.net/attachments/901270821715210260/901270895446863912/neet-anime.png"
},
{
"gif": "https://tenor.com/view/kanna-kamui-pat-head-pat-gif-12018819"
},
{
"gif": "https://tenor.com/view/pat-head-gakuen-babysitters-kotarou-anime-cute-gif-17907437"
},
{
"gif": "https://tenor.com/view/umaru-frown-happy-feeling-better-pat-gif-10947495"
}
]
You should call randomObject like this: randomObject(pat.responseJSON); or
$.getJSON( "../data/random/anime/pat/pat.json", function( data ) {
randomObject(data);
})
I'm unable to reproduce the same issue you're having, but the only thing I needed to change to get this working was to Stringify the object, so that I had it's content as a plain string.
This can then be applied to the HTML element
function randomObject(obj) {
const arr = Object.values(obj); // Is this necessary? It works fine for me without, since the data is already an array
const randomValue = Math.floor(Math.random() * arr.length); // As a variable to make it clearer what this is for
// "Stringify" (Turn it into a string) first, then we can apply it to the HTML element's content as a plain string
document.getElementById("content").innerHTML = JSON.stringify(arr[randomValue]);
}