Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading