2

I need to create HTML selectors and to get their values from JSON, I created JSON and tried to read it simply by adding one more in html document and then just parse into variable with JS, but it doesn't work, answers which I found didn't really help.

HTML:

<body>
    <form>
        <label>Select list</label>
        <select id = "Coutries">

        </select>
        <select id = "Bands">

        </select>
        <select id = "Albums">

        </select>   
    </form> 
    <script src="data.json"></script>
    <script src="script.js"></script>
</body>

JavaScript:

const data = JSON.parse(data);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Sveti
  • 23
  • 4

2 Answers2

2

You can't load JSON through a script element. Instead, in your script.js, you can fetch it:

fetch("data.json")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.json();
})
.then(data => {
    // Use the data here, it's been parsed
})
.catch(error => {
    // Handle/report error here
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-2

Have you tried this:

$.getJSON('yourFile.json', function(data) {
    var arr= [];
      $.each( data, function( key, val ) {
    var tempArr=[key,val]
        arr.push( tempArr );
      });
    });
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
Roshini
  • 11
  • 3
  • There's no indication in the question of the user using jQuery. Neither is there any indication that they want to convert `data` into an array of arrays. – T.J. Crowder Jun 13 '19 at 07:30