The JSON file that you posted contains two nights of sleep data. How many nights of data do you have in total?
Recall this line from this post:
data = sleep[0]["levels"]["data"];
The first subscript, which is 0
in the above line, represents the index of the night for which you are processing data. To get past the first night, you can create a variable, as follows, to count up through the nights:
let night = 0;
Then you can use this:
data = sleep[night]["levels"]["data"];
Whenever you finish off the last piece of data for a given night, increment the night
variable by 1
to get to the data for the next night.
EDIT (August 27, 2021):
In order to process data for multiple nights, when it is possible for nights to differ in the number of readings, you will also need to depart from the technique of using frameCount
to calculate an index to the data.
Try out the code below, and feel free to refine it to suit your needs. Note that the variable name night_index
is used instead of the name night
that was suggested above.
let sleep, night_data;
let num_nights; // number of nights of data
let new_night = true; // starting data for a new night
let night_index = 0; // index for each night
let night_data_length; // number of data points for a night
let night_data_index; // index for data points for a night
function preload(){
sleep = loadJSON("data/sleep-2020-04-30.json");
}
function setup() {
createCanvas(windowWidth, windowHeight);
num_nights = Object.keys(sleep).length;
colorMode(HSB, 360, 100, 100, 100);
frameRate(1);
textSize(24);
}
function draw() {
if (new_night) {
// starting a new night of data
night_data = sleep[night_index]["levels"]["data"];
night_data_length = night_data.length;
new_night = false;
night_data_index = 0;
}
let sleepLevel = night_data[night_data_index]["level"];
let dateTime = night_data[night_data_index]["dateTime"];
if (sleepLevel == ["wake"]){
//frameCount = 0;
background(0, 100, 100);
}
if (sleepLevel == ["deep"]){
background(100, 100, 100);
}
if (sleepLevel == ["light"]){
background(200, 100, 100);
}
if (sleepLevel == ["rem"]){
background(300, 100, 100);
}
text(dateTime, 40, 40);
text("Night: " + night_index + " Reading: " + night_data_index, 40, 80);
text(sleepLevel, 40, 120);
night_data_index += 1;
if (night_data_index === night_data_length) {
// have processed all data for a night
new_night = true;
night_index += 1;
// are there any more nights?
if (night_index === num_nights) {
noLoop();
}
}
}