Mastering the art of correctly parsing JSON files with pure JavaScript

I've been struggling with creating HTML selectors and retrieving their values from JSON. I attempted to read the JSON data by adding a script tag to the HTML document and parsing it into a variable using JavaScript. However, this approach didn't seem to work as expected, and the solutions I found online were not very helpful.

Here is the HTML setup:

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

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

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

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

And the JavaScript code snippet:

const data = JSON.parse(data);

Answer №1

If you need to retrieve JSON data, using a script tag will not work. Instead, you can fetch the JSON data in your script.js file by utilizing the fetch method:

fetch("data.json")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.json();
})
.then(data => {
    // Utilize the parsed data here
})
.catch(error => {
    // Handle or report any errors here
});

Answer №2

Did you give this a shot:

$.get('yourData.json', function(info) {
    var array= [];
      $.each( info, function( index, value ) {
    var tempArray=[index,value]
        array.push( tempArray );
      });
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

What is the method for React to tap into the local variables of Hooks functions?

Here we have a basic hook example function App() { let [counter, setCounter] = useState(0); return <button onClick={() => setCounter(counter + 1)}>{counter}</button>; } My understanding of React operation is: React will invoke App() to ...

Vue router is designed to maintain the state of child components without requiring them to

Encountering a strange problem with vue-router. Developed a simple CRUD app for managing users. The app includes four main views: User list and a create button Create view with a form child component that fetches field data from an API within the creat ...

Avoid using the JavaScript 'Sys.WebForms..' function if there is no ScriptManager present on the page

Currently, I am using a single JavaScript binding in the Master Page for my entire project. However, the Master Page does not include a ScriptManager. This means that some pages have Ajax components, such as UpdatePanel, while others do not. The 'Sys. ...

I'm looking to include an icon in my TreeItem component in Material UI 4. How

I have a unique menu created using MATERIAL UI 4, consisting of a primary TreeItem for the main menu and a secondary TreeItem for the submenu sections. I am looking to assign a specific icon to each main menu label. How can I achieve this? Additionally, ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

The function socket.on(..) is not being triggered

Currently, I am in the process of developing a straightforward website to showcase socket communication and chat capabilities. The server side is coded using Python Flask app, while the client-side utilizes JavaScript. Below is an excerpt from the server c ...

Mastering state management for various input types in React

Developing a proof of concept for showcasing tennis player details on a webpage. The page can display information for any number of players, and the user should be able to update all player details simultaneously. I have created 3 components: PlayersPage, ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

Generating a safe POST connection with express.js

Is there a simple method to generate a link for submitting a POST request using Express.js or a plugin? This approach can also be employed to enhance security for important actions like user deletion, including CSRF protection. In some PHP frameworks lik ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

The cell text you are trying to access is beyond the allowed range

I am currently developing a shopping application, but I have encountered a problem. Up to this point, I have been parsing JSON data and creating tableview cells. However, I am facing an issue where it is showing an 'index out of range' error: ov ...

Utilize JSON to populate ImageAdapter with images

Hey there! I recently tried out a GridView demo from this link The demo worked perfectly, but now I'm looking to retrieve images from a server database. To achieve this, I implemented a handler class that interacts with the server and retrieves image ...

What is the purpose of incorporating .prototype within the function?

I came across John Resig's slideshow at http://ejohn.org/apps/learn/#78 I'm a bit confused about the necessity of using .prototype in the statement Me.prototype = new Person(); function Person(){} Person.prototype.getName = function(){ return ...

Gson's Nested Class Functionality

I am relatively new to using Gson and I'm currently working with a json response from an api that has nested structures. To handle this, I have defined the following nested classes - public class GsOrgIds { public GsOrgIdsData data; publi ...

Indicate the end of the row in JavaScript when using the match() function

What's the best way to identify the end of a row when using the match() function? I'm trying to extract "2021 JANUARY 18 MONDAY" from this page. https://i.sstatic.net/bTNdQ.png https://i.sstatic.net/YzFs2.png If there is additional text after ...

Wookmark js isn't designed to generate columns from scratch

I am attempting to utilize the Wookmark jQuery plugin in order to create a layout similar to Pinterest. However, I am encountering an issue where Wookmark is not creating columns within the li elements, instead it is simply stacking images on top of each o ...

Circular JSON error in Google Realtime occurs specifically when the indexReference is stored within a collaborative map and is contained within an object

While attempting to save indexReferences for each user, I have noticed that storing them directly in a map works without any issues. However, if they are stored in an object or a custom realtime object, the realtime API throws Circular JSON errors. The fo ...

How to Extract Nested JSON Data in Java using Regular Expressions

Exploring the world of regex, I am on a mission to convert nested JSON into strings. Check out some sample examples below: My desired output string format is as follows: {"mainId":"12345","binaries":[{"subId":"123456bd","splitAll":true},{"subId":"123456c ...