Read JSON and images in preload()

Hello, I have a question about p5.js preload function.

I want to read JSON and images in my p5.js sketch,
and JSON has images information (number of files, names, id).
So I write a code and JSON as follows, but it doesn't work properly.
I think JSON value is not read normally or not on time in preload function.
I wonder how I can resolve this problem. Please your help!


var data;  
var images = [];  
var itemNum;  

function preload() {  
    data = loadJSON("./data.json");  

    itemNum = Object.keys(data).length;  
    console.log(itemNum); // output "0", but this is actually "3"  

    for (var i = 0; i < itemNum; i++) {  
        images[i] = loadImage("./images/image" + data[i].imageId + ".png");  
    }  
}  

function setup() {  
    createCanvas(100, 100);  
    image(images[0], 0, 0);  
}  

[{
        "name": "AAA",
        "imageId": "100"
    },
    {
        "name": "BBB",
        "imageId": "200"
    },
    {
        "name": "CCC",
        "imageId": "300"
    }
]
Sign In or Register to comment.