Home > OS >  How to display .json file on webpage when it's in a <script> tag?
How to display .json file on webpage when it's in a <script> tag?

Time:05-22

Is there a way to manipulate and display the data in the file without using fetch? In addition, can I store the json file in a variable and iterate through it? It just seems that for a local file there would be a simpler method of working with/displaying the data...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href ="styles.css">
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
    <script src="main.js"></script>
    <script src="animals.json"></script> <!-- added json file-->
</head>
<body>

<div class ="sampleDiv"></div>
</div>
    
</body>
</html>

json file

[
    {
      "name": "Whiskers",
      "species" : "cat",
      "foods": {
        "likes": ["celery", "strawberries"],
        "dislikes": ["carrots"]
      }
    },
    {
      "name": "Woof",
      "species" : "dog",
      "foods": {
        "likes": ["dog food"],
        "dislikes": ["cat food"]
      }
    },
    {
      "name": "Fluffy",
      "species" : "cat",
      "foods": {
        "likes": ["canned food"],
        "dislikes": ["dry food"]
      }
    }
  ]

CodePudding user response:

Yes you can just put the JSON file in a js file with parsing const yourJSON = JSON.parse(/*paste your entire JSON*/) and then add the js file in script tag so you can accesses yourJSON variable in the other js files.

CodePudding user response:

<script> elements are for loading JavaScript, not JSON.

<script src="animals.json"></script> is just going to cause the browser to throw a CORB error when it doesn't get the content-type it is expecting.

Use the fetch API to load the JSON instead.

fetch("animals.json")
    .then(response => response.json())
    .then(data => {
        // Work with your data here
    });

CodePudding user response:

You cannot load .json files as scripts. You'll need JavaScript code and an HTTP request to load it. This can be done easily by fetch(), but if you're just looking for an alternative, you can use jQuery's $.getJSON:

$.getJSON('animals.json', function(obj) {
    document.getElementsByClassName('sampleDiv')[0].innerHTML = JSON.stringify(obj);
});

In my opinion, the most elegant way to do it is with fetch(). Dumping the whole json in the JavaScript code and using JSON.parse makes everything extremely unmaintainable and using jQuery is overkill, too.

  • Related