Skip to content
Advertisement

Access json data from external file

I am trying to load/read data from a local json file using JQuery/Javascript. Everything I have tried so far is throwing me CORS policy error. I don’t know how to resolve this.

<html>

<body>

  <div>
    <a href="#" id="fetch">Fetch JSON</a>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(function() {
      $('#fetch').click(function() {
        $.getJSON('music.json', function(data) {
          albums = data['Albums']

          console.log(albums)
        })
      });
    })
  </script>

</body>

</html>

Json file –

{
  "Albums": [{
      "albumName": "Desire",
      "artist": "Bob Dylan"
    },
    {
      "albumName": "Live in London",
      "artist": "Leonard Cohen"
    },
    {
      "albumName": "Abbey Road",
      "artist": "The Beatles"
    },
    {
      "albumName": "Blackstar",
      "artist": "David Bowie"
    }
  ]
}

How to get this running?

Advertisement

Answer

You should run your project on the web server, in this case, you can do this:

data.json

{
 "albums": [
  {
   "name": "First Album",
   "artist": "Leonard Cohen"
  }
 ]
}

in html or js file:

fetch('http://127.0.0.1:5500/data.json')
    .then(response => response.json())
    .then(json => console.log(json))

in this case, my webserver local address is http://127.0.0.1:5500

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement