is the JSON data saved in the right variable

Viewed 21

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);
    }
    );
1 Answers

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();
Related