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);
0

2 Answers 2

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
});
Sign up to request clarification or add additional context in comments.

Comments

-2

Have you tried this:

$.getJSON('yourFile.json', function(data) {
    var arr= [];
      $.each( data, function( key, val ) {
    var tempArr=[key,val]
        arr.push( tempArr );
      });
    });

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.