What is the proper method for showcasing a .json file on a webpage within a <script> tag?

Is there an alternative method to manipulate and showcase the data in a file without utilizing fetch? Moreover, is it possible to save the JSON file in a variable and iterate over its content? It appears that for a local file, there should be a more straightforward approach to working with and 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"]
      }
    }
  ]

Answer №1

<script> tags are meant for JavaScript, not JSON data.

If you use

<script src="animals.json"></script>
, the browser will trigger a CORB error because the content-type won't match what it expects.

To load JSON data, utilize the fetch API instead.

fetch("animals.json")
    .then(response => response.json())
    .then(data => {
        // Handle the data here
    });

Answer №2

A simple way to incorporate a JSON file into your JavaScript project is by placing the JSON data within a JS file using the syntax

const myData = JSON.parse(/*your JSON data here*/)
. Next, include the JS file in a script tag to access the 'myData' variable from other JS files.

Answer №3

If you're trying to load .json files as scripts, remember that you cannot do so directly. You'll need to utilize JavaScript code along with an HTTP request in order to load it properly. One simple method is to use the fetch() function. Alternatively, you can also make use of jQuery's $.getJSON method:

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

From my perspective, employing fetch() is the most elegant approach. Attempting to include the entire json within the JavaScript code and then utilizing JSON.parse can lead to extreme difficulties in maintenance. Similarly, resorting to jQuery may be excessive for this task.

Answer №4

If you need to access local JSON data using vanilla JavaScript, consider setting up a node web server. However, if all you want to do is display your data without any changes, simply create a file named data.json with information about your animals.

const animals = [
    // Add your animal objects here
]

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

Click to switch the content using ng-click

I have a query that iterates through an array of strings called wikiContent. After displaying the first three sentences from the array, I aim to insert a hyperlink labeled More, which when clicked will reveal the remaining sentences. This code snippet is ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

The process of saving report filters and making them accessible for both running and scheduling tasks

I am facing a use case where I need to add query parameters to API calls and save them for future use. Essentially, I have a report that requires multiple filters to be saved - some predefined and others customizable. These saved filters can then be execut ...

Issues with rendering a list in React-NextJs using data fetched from a fake API

I'm encountering an issue with my nextJS app where a list is not rendering properly. The list should display items from an array of objects called productList. I'm attempting to render the productList starting on line 26 in the code below: https ...

Transmit data from a child component to its parent in React

I have a situation where I want to organize the inputs and button in separate components, but I'm having trouble accessing the state of the inputs from the parent component. How can I successfully catch and use those values for submission? export defa ...

Does using the useState() hook in React automatically empty out the input fields?

Every time I update a state in my React application, it mysteriously erases the content of my inputs like checkboxes and numbers. Let me share a simple example to demonstrate this issue. import React, { useState } from "react"; export default fun ...

Begin executing a JavaScript function upon receiving a POST request through AJAX

I'm currently working on coding a JavaScript script that initiates an AJAX POST request to a PHP page containing another JavaScript. I need the JavaScript in the PHP page to automatically execute after receiving the response from AJAX. Unfortunately, ...

Utilizing the React useEffect hook for implementing a complex, extended task while efficiently merging the

As I navigate through a situation where a user has the ability to upload files via drag-and-drop, I find myself employing a technique utilizing an empty dependency array to establish an RXJS subscription responsible for managing dropped files and upload ti ...

Implementing the Google Maps API into a React application to generate a customized route between two specified points

I'm currently developing a React application that is designed to display the distance between two points on a map. Although I successfully implemented this feature using JavaScript and HTML, I am facing challenges in converting it to React as I am re ...

What steps do I need to take in order to host my webpage on my Mac's localhost?

Currently, I am developing a webpage and I want to test how it appears on my iPhone's Safari browser. Since the project is still in the development stage, I don't plan on purchasing a domain or hosting just yet. My goal is to temporarily view it ...

How can Google Cloud Vision be optimized to enhance OCR capabilities?

Recently, I decided to put Google cloud vision's OCR to the test, only to be disappointed by the subpar results. Despite my documents being in French, the OCR seemed to struggle with detecting apostrophes and commas accurately. For instance, when usin ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

What is the best way to personalize the appearance of an Angular Material Input?

I'm currently collaborating with a freelance client who is keen on incorporating Angular Material into our project. However, they are not satisfied with the appearance of the underline in the angular material input field. Despite my efforts to modify ...

Validation of input in React using the onChange event handler

When trying to validate a numeric input using onChange in React, I encountered an issue where the input clears and React throws a ReferenceError: value is not defined. This error makes sense since there is nothing to validate when the input is empty. I ca ...

Discover the seamless process of dynamically adjusting metadata to reflect current state values within the Next.js app directory

Exploring the app directory within Next.js version 13, I came across a change in the official documentation where they have replaced the old head method with metadata. Initially, I thought this feature was only available on page or layout components. Now, ...

Presentation with multi-directional animations

Curious to know if it's possible to create a unique slideshow that scrolls in multiple directions? The concept is to display various projects when scrolling up and down, and different images within each project when scrolling left and right. Is this i ...

Is there a way to configure a Mui textfield to only allow numeric input? It currently accepts numbers, the letter "e," and dashes

Take a look at my current code. <TextField error={values[1].error} fullWidth id="id" type="number" value={values[1].Id} placeholder='Enter ID' onChange={handleChange(1,'Id')} variant="outlined" inputProps={{min: 0,inputMode: &apos ...

The AngularJS error message states that there is an issue because the $resource function is

I am currently facing an issue with my controller, specifically the error message: TypeError: $resource is not a function This error is pointing to the line var Activities = $resource('/api/activities'); app.controller('AddActivityCtrl& ...

What are the steps to successfully install the movie-trailer npm package while avoiding any potential errors?

Is there a way to successfully install the movie-trailer npm package without encountering these issues? $ npm I movie-trailer npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead. npm ERR! code E404 npm ERR! 404 No ...