Has the JSON information been stored in the correct variable?

I'm trying to store the JSON data from the file named a5.json in a variable called rects. However, I am not sure if I did it correctly. My goal is to display rectangles using the rects variable. Can someone guide me on how to achieve that?

<script src="a5.json" defer></script>


<canvas id="c" width="500" height="500"></canvas>

    var canvas = document.getElementById("c");
    var context = canvas.getContext("2d");
    var json = [{x: "50", y: "50", w: "100", h: "50", f: true }, { x: "50", y: "150", w: "100", h: "50", f: false }];
    var rects = json;

    context.lineWidth = 2;
    context.strokeStyle = "#FF0000";
    context.fillStyle = "#FF0000";
    json.forEach(shape => 
    {
        context[shape.f === true ? 'fillRect' : 'strokeRect'](shape.x, shape.y, shape.w, shape.h);
    }
    );

Answer №1

When it comes to loading JavaScript, the <script> element plays a crucial role. However, if you attempt to load a JSON file with it, several things could happen:

  • It may try to execute the JSON file as JavaScript and encounter an error.
  • It could also try to execute the JSON file as JavaScript, produce some literal value, and then discard it since the file does not contain any executable JS code.
  • Alternatively, the Content-Type HTTP response header may indicate that the file is not JavaScript, prompting the browser to do nothing or issue a warning in the developer tools console.

If your goal is to read data from a JSON file, using Ajax is recommended. One popular method involves leveraging the Fetch API:

const response = await fetch("a5.json");
const rects = await response.json();

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

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

What is the best way to extract information from a nested JSON structure without keys in an Android application?

Here is a sample JSON structure that I have: [ [ "{"category_id":1,"category_name":"1Appetizers","image_id":0}", "{"category_id":13,"category_name":"Buffet","image_id":0}" ], [ "{"subcategory_id":1,"category_id":12,"subcategory_name":"Beer","image_id":0} ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

Vue Filtering and Pagination Implementation

In Vue pagination, how can you control the number of array objects to be displayed based on a user-selected amount like 10, 15, or 25? I successfully implemented rendering 10 items per page and it's functioning smoothly. ...

The Vuex store variable is being accessed prior to being populated with information retrieved from the API

I am currently attempting to retrieve data from an API using Vuex. Below is the action function in the Vuex store: async getEpisodeFromApi({ commit }, id) { const data = { id }; return await axios.get(Api.getUrl(data)).then((res ...

Strategies for incorporating a JSON variable into the HttpClient query parameters in an Ionic 5 application

Currently using Ionic 5 and attempting to retrieve the IP address of the client user to include it in a URL. Here is my code: this.ipclient = this.httpClient.get("https://api.ipify.org/?format=json"); this.ipclient .subscribe(ipclient => { console.log( ...

How to submit form data with a POST request in Flask using fetch without having to reload

Despite reading numerous similar questions, I am still unable to determine how to achieve my goal. I have multiple forms on a single page and I am trying to submit data from each form without refreshing the page. Below is an example of one of the five form ...

Docker: The container did not generate any output files

The docker image I created is designed to execute a python script that scrapes data from a website and saves it into a json file within the same directory. When running the python script independently, the json file is generated successfully. However, I ...

"Compactly condensing" an abundance of boolean values in JSON through manual effort

We are dealing with a data model that consists of 600 boolean values per entity. This entire dataset needs to be transmitted from a node.js backend to an Angular frontend via JSON. Considering the internal nature of this API (not public), our primary focu ...

What is the best way to incorporate multiple versions of jQuery on one webpage?

Is it possible to use multiple versions of jQuery on a single page? I need two different versions for various functions, but they seem to be conflicting with each other. If I implement jQuery noconflict, will the product scripts still work? <script typ ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...

Steps to update the first set of x documents in MongoDB using Mongoose

Is there an efficient way to update the first five documents in mongoose? While I am familiar with updating multiple documents based on a condition, I specifically want to target the first five documents for updating in mongoose. I understand that I can a ...

What is the maximum level of referencing allowed in v-if conditions?

I'm encountering an issue with some markup I have: <div class="form-group" v-if="model.owner.enabled"> The model object in the scope is structured like this: { ... owner: { enabled: true ... } ... } However, Vue is th ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

Retrieve the individual character styles within an element using JavaScript

I'm currently dealing with a dynamically created div that features styled characters like: <div>Hello <b>J</b>oe</div> and my goal is to identify which characters are styled (in this case, the letter J). I've already atte ...

Setting default values for route parameters in JavaScript

I'm looking to streamline my JavaScript code by simplifying it. It involves passing in 2 route parameters that are then multiplied together. My goal is to assign default values to the parameters if nothing is passed in, such as setting both firstnum ...

Navigating through nested hash structures in Ruby

There is a json file provided containing various public holidays: { "public_holidays": [ { "date": "2013/1/1", "name": "New Years Day" }, { "date": "2013/1/21", "name": "Luther King Day" }, { "date": "2013/5/27", "name": "Memorial Day" } ] } The objecti ...

When using WYSIWYG editors, be on the lookout for empty paragraphs and incorrect code in CSS, JavaScript, and

I am currently in the process of redesigning a website for a client. The site is already built using Joomla 1.7, but I am facing an issue with the articles section that was created by the client using a WYSIWYG editor. The problem lies in the messy code st ...

How can we prevent the automatic redirection to the home page index.html?

The page you are trying to access contains data that you previously entered. Revisiting the page may result in repeating any actions you have taken. Do you wish to proceed? Upon refresh, this message appears and the form data is resubmitted to Flask. How ...

Sequential invocations to console.log yield varying outcomes

So, I'm feeling a bit perplexed by this situation. (and maybe I'm missing something obvious but...) I have 2 consecutive calls to console.log. There is nothing else between them console.log($state); console.log($state.current); and here's ...