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

142
Visualizações
Trying to read a JSON file with a JS script in HTML

I am trying to use my json file, busesNotArrived.json and put its contents in a <p>, however it is not working and the data in the JSON file is not displaying, here is my code:

<p>Buses Not Arrived:<br><br><span id="output"></p>

<script>
  const fs = require('fs')
  fs.readFile('json/busesNotArrived.json', 'utf8', (err, jsonString) => {
      if (err) {
          alert('Error reading Database:', err)
          return
      }
      try {
          const bus = JSON.parse(jsonString)
          alert("Bus address is:", bus.busNumber)
          document.getElementById('output').innerHTML = bus.BusNumber;
  } catch(err) {
          alert('Error parsing JSON string:', err)
      }
  })
</script>

Inside of my JSON file, this is what is stored:

{
    "busRoute": 123123,
    "busNumber": 123123
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Well, I eventually figured it out, so like what @Ronnel said, you cannot use require() because that is node.js and not javascript, so you would have to use the fetch() api to get the .json file.

For anyone who would like to see the code, here it is:

<div id="myData" class='absolute1' onclick='notArrived()'><strong><u>Not Yet Arrived</u></strong><br><br></div>

<script>
        fetch('json/busesNotArrived.json')
              .then(function (response) {
                  return response.json();
              })
              .then(function (data) {
                  appendData(data);
              })
              .catch(function (err) {
                  console.log('error: ' + err);
              });
          function appendData(data) {
              var mainContainer = document.getElementById("myData");
              for (var i = 0; i < data.length; i++) {
                  var div = document.createElement("div");
                  div.innerHTML = 'Bus Number: ' + data[i].busNumber + "<br>" + 'Bus Route:' + ' ' + data[i].busRoute + "<br><br>";
                  mainContainer.appendChild(div);
              }
          }

</script>

|| Sorry about the Indents :P ||

And also, here is what was in the .json file so you can work off of it:

[
    {
        "id": "1",
        "busNumber": "4024",
        "busRoute": "44444"
    },
    {
        "id": "2",
        "busNumber": "4044",
        "busRoute": "4444"
    },
    {
        "id": "3",
        "busNumber": "5024",
        "busRoute": "55555"
    }
]

Good Luck using this!

If you wanted more explanation, here is where I got the code from:

(https://howtocreateapps.com/fetch-and-display-json-html-javascript/)

about 4 years ago · Juan Pablo Isaza Relatório

0

Javascript is not the same as node.js require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.

You might need to directly include the modules; some of the modules might not work in the browser sandbox context.

Also, tools such as http://browserify.org/ might be useful.

And please put the error message 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