-1

im supposed to save the json data from the a5.json file into a variable Called rects. I have the feeling I did it wrong. Im supposed to display the rectangles through the rects variable. how do I do 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);
    }
    );
Jenni
  • 11
  • 2
  • 1
    *"I have the feeling I did it wrong."* - Have you tested and debugged the code to find out? Is there a specific observable problem you've encountered? "I have the feeling I did it wrong" is solved by "having the feeling you did it right". But if there's a specific problem you've encountered, we can help with that. – David Sep 22 '22 at 11:43
  • Does this answer your question? [HTML/Javascript: how to access JSON data loaded in a script tag with src set](https://stackoverflow.com/questions/13515141/html-javascript-how-to-access-json-data-loaded-in-a-script-tag-with-src-set) – jabaa Sep 22 '22 at 11:47
  • `[{x: "50", y: "50", w: "100", h: "50", f: true }, { x: "50", y: "150", w: "100", h: "50", f: false }]` is a JavaScript object literal and not valid JSON. The variable name `json` is confusing. You can't load JSON using a `script` tag. – jabaa Sep 22 '22 at 11:48

1 Answers1

1

The <script> element is for loading JavaScript. If you point it at a JSON file then it will either:

  • Try to execute it as JS and error
  • Try to execute it as JS, generate some literal value, then discard it as nothing is done with it by the "JS" in the file
  • Read the Content-Type HTTP response header, recognise that it is not JS, and do nothing (possibly throwing a warning to the developer tools console).

If you want to read data from a JSON file, use Ajax. The usual way is to use the Fetch API.

const response = await fetch("a5.json");
const rects = await response.json();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335