JSON file not being read correctly

Hi @fleshcircuit,

Your data/sleep-2020-04-30.json file needs a ] at the end.

To get things working, try this, then you can modify and build upon it as you wish, in order to complete your script:


let secs = 0;
// let list1 = [];
let sleep, data;

function preload(){
  //Load list of json file names
  //list1 = loadStrings('dataList.txt');
  sleep = loadJSON("data/sleep-2020-04-30.json");
  
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 360, 100, 100, 100);
  data = sleep[0]["levels"]["data"];
  frameRate(1);
}

function draw() {
    let sleepLevel = data[frameCount % data.length]["level"];
    print(sleepLevel)
    
    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);
    }

  }

EDITED on August 19, 2021 to add the following:

Essentially, the main problem was not properly drilling down into the information from the .json file. This, in the setup() function, helps get to what you need:

  data = sleep[0]["levels"]["data"];

Using [0] gets to the extensive object inside the opening square bracket. From there we need to get into the "levels" and "data" attributes, respectively.

1 Like