How to access JSON data loaded in a script tag with src set with JavaScript?

Spread the love

To access JSON data loaded in a script tag with src set with JavaScript, we call the JSON.parse method.

For instance, we write

window.myJSON = {
  id: "12ws",
  name: "smith",
};

in my-json.js to add a global variable with the JSON.

Then we write

<script src="my-json.js"></script>
<script>
  document.getElementById("json-holder").innerHTML = JSON.stringify(myJSON);
</script>

to load my-json.js with the script tag.

And then we convert the myJSON variable to a string with JSON.stringify and then set that as the HTML content of the element with ID json-builder.

Leave a Reply

Your email address will not be published. Required fields are marked *