Trying to load an array from a JSON

Hello!

So, I’m trying to get data from a JSON file, where the data was saved as an array. But when I try to retrieve discrete values, they come back as ‘undefined’.

Can you help? What am I doing wrong?

let locJ = 'designs.json';
    jL = loadJSON(locJ);
    
  
    console.log(jL.boxs[0].e);

Console = Cannot read property ‘0’ of undefined

This is what the successfully(?) saved JSON file looks like (generated from p5 code):

{
  "boxs": [
    {
      "x": 73.1,
      "y": 73.1,
      "r": 34.4,
      "gX": 1,
      "gY": 1,
      "h": false,
      "p": false,
      "e": false
    },
    {
      "x": 73.1,
      "y": 107.5,
      "r": 34.4,
      "gX": 1,
      "gY": 2,
      "h": false,
      "p": false,
      "e": false
    },
    {
      "x": 73.1,
      "y": 141.89999999999998,
      "r": 34.4,
      "gX": 1,
      "gY": 3,
      "h": false,
      "p": false,
      "e": false
    },

**etc**

Thanks for any help :slight_smile:

B

1 Like

…And solved!

My code wasn’t giving the JSON file long enough to load :sweat_smile:

So, have made sure that the file is successfully loaded in the preload() function.

Shiffman’s video is great on this topic: Giant Eagles

B x

2 Likes

nice one! In the future if you dont want to preload, you could use a callback to call a function once the data is ready to be processed there is an example in the p5 reference 1/2 way down here: https://p5js.org/reference/#/p5/loadJSON

Here’s an example using an arrow function to offer another direction from the p5js documentation
( :warning: pseudo-code ahead)

  let locJ = 'designs.json';
  jL = loadJSON(locJ, (incomingData)=>{
    //code to execute once the incoming data has fully loaded, this is a callback
    console.log(jL.boxs[0].e);
  });
1 Like

Brilliant, thank you!