-1

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.

Ashar
  • 724
  • 10
  • 30
  • Are you using pure JavaScript or are you using Node/a Node-based framework? – Tiramonium Dec 10 '21 at 20:13
  • I'm using pure JavaScript. – Ashar Dec 10 '21 at 20:13
  • Why wouldn't you just `fetch` it instead...? – esqew Dec 10 '21 at 20:17
  • Does this answer your question? [HTML/Javascript: how to access JSON data loaded in a script tag with src set](https://stackoverflow.com/questions/13515141/html-javascript-how-to-access-json-data-loaded-in-a-script-tag-with-src-set) – esqew Dec 10 '21 at 20:18
  • @esqew Can you provide a code snippet please? – Ashar Dec 10 '21 at 20:18
  • @esqew - Oh no - that answer (your dup) was from 3 years ago. The easiest solution is for the OP to use and `import` statement in a separate JavaScript file. – Randy Casburn Dec 10 '21 at 20:19
  • If this is just static data, here is a working example that is similar to Tiramonium's answer: https://stackblitz.com/edit/js-jcat6q?file=index.js – Randy Casburn Dec 10 '21 at 20:25

2 Answers2

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));
esqew
  • 42,425
  • 27
  • 92
  • 132
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>
Tiramonium
  • 557
  • 5
  • 15