Categories
JavaScript Answers

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

Spread the love

If you load JSON data using a <script> tag with the src attribute pointing to a JSON file or a JSONP endpoint, we can access the loaded data using JavaScript.

To do this, we:

Assuming you have a JSON file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
  1. In your HTML file, load the JSON data using a <script> tag with the src attribute pointing to the JSON file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Access JSON Data</title>
</head>
<body>
  <script src="data.json"></script>
  <script src="script.js"></script>
</body>
</html>
  1. In your JavaScript file (script.js), access the loaded JSON data:
// Access the global variable that holds the JSON data
console.log(jsonData);

// Access specific properties
console.log('Name:', jsonData.name);
console.log('Age:', jsonData.age);
console.log('City:', jsonData.city);

This assumes that the JSON file is structured as an object, and it will be loaded into a global variable named jsonData.

After the script tag with the JSON file is executed, you can access the JSON data in your JavaScript code just like you would access any other JavaScript object.

Note: Make sure that the server hosting the JSON file allows CORS (Cross-Origin Resource Sharing) if the HTML file is hosted on a different domain. Otherwise, you might encounter CORS errors.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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