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

232
Visualizações
Javascript load all the keys in external JSON

I have external JSON at location /data/words.json

{
    "sports":       ["golf", "hockey", "football"],
    "animals":      ["giraffe", "snake", "lizard", "puma"],
    "video games":  ["pacman", "asteroids", "super mario brothers", "donkey kong"]
}

I need to access this in my javascript function. I have loaded the file as follows:

<script type="text/javascript" src="./data/words.json"></script>

How can I print all the keys of given JSON and print it on browser? Note that provided JSON does not have a variable name.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

JSON was never meant to be loaded this way, as you've probably come to find out. Why not just use fetch instead (if your expected execution environment supports it)?

const jsonData = await fetch('./data/words.json').then(res => res.json());

Depending on what exactly you have in mind when you say "print all the keys of given JSON and print it on browser", you could accomplish that pretty easily:

Object.keys(jsonData).forEach(key => console.log(key));
about 4 years ago · Santiago Gelvez Relatório

0

Write a native ECMAScript module that loads the JSON into a constant and then manipulates it. No need to import it before the script runs either.

EDIT:

Having forgotten my older ways of working with pure JavaScript, just remembered you'll also need a web server running on your local machine to be able to properly load resources, even if they are stored locally.

<script type="module">
  import * as words from './data/words.json';

  const wordsObj = JSON.parse(words);
  const wordsKeys = Object.keys(wordsObj);
  const wordsSpan = document.createElement("span");

  for (let i = 0; i < wordsKeys.length; i++) {
    wordsSpan.innerHTML += wordsKeys[i] + "<br>";
  }

  document.getElementByTagName("body").appendChild(span);
</script>
about 4 years ago · Santiago Gelvez 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