Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
How to display .json file on webpage when it's in a <script> tag?

Is there a way to manipulate and display the data in the file without using fetch? In addition, can I store the json file in a variable and iterate through it? It just seems that for a local file there would be a simpler method of working with/displaying the data...

<!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></title>
    <link rel="stylesheet" href ="styles.css">
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
    <script src="main.js"></script>
    <script src="animals.json"></script> <!-- added json file-->
</head>
<body>

<div class ="sampleDiv"></div>
</div>
    
</body>
</html>

json file

[
    {
      "name": "Whiskers",
      "species" : "cat",
      "foods": {
        "likes": ["celery", "strawberries"],
        "dislikes": ["carrots"]
      }
    },
    {
      "name": "Woof",
      "species" : "dog",
      "foods": {
        "likes": ["dog food"],
        "dislikes": ["cat food"]
      }
    },
    {
      "name": "Fluffy",
      "species" : "cat",
      "foods": {
        "likes": ["canned food"],
        "dislikes": ["dry food"]
      }
    }
  ]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

<script> elements are for loading JavaScript, not JSON.

<script src="animals.json"></script> is just going to cause the browser to throw a CORB error when it doesn't get the content-type it is expecting.

Use the fetch API to load the JSON instead.

fetch("animals.json")
    .then(response => response.json())
    .then(data => {
        // Work with your data here
    });
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes you can just put the JSON file in a js file with parsing const yourJSON = JSON.parse(/*paste your entire JSON*/) and then add the js file in script tag so you can accesses yourJSON variable in the other js files.

about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot load .json files as scripts. You'll need JavaScript code and an HTTP request to load it. This can be done easily by fetch(), but if you're just looking for an alternative, you can use jQuery's $.getJSON:

$.getJSON('animals.json', function(obj) {
    document.getElementsByClassName('sampleDiv')[0].innerHTML = JSON.stringify(obj);
});

In my opinion, the most elegant way to do it is with fetch(). Dumping the whole json in the JavaScript code and using JSON.parse makes everything extremely unmaintainable and using jQuery is overkill, too.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda