He intentado mostrar los datos JSON en la página HTML pero, extrañamente, no muestra los datos JSON pero muestra esto .
El mismo código funciona bien si se elimina la línea inner.HTML y se usa console.log en su lugar, este es el resultado si se usa console.log en lugar de inner.HTML .
Código:
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>Los datos JSON:
[ { "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" } ]Deberías llamar a randomObject así: randomObject(pat.responseJSON); o
$.getJSON( "../data/random/anime/pat/pat.json", function( data ) { randomObject(data); })No puedo reproducir el mismo problema que está teniendo, pero lo único que necesitaba cambiar para que esto funcionara era Stringificar el objeto, de modo que tuviera su contenido como una cadena simple.
Esto se puede aplicar al elemento HTML.
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]); }