Iterate throw JSON array values

Hi mloiz!
The issue is that the array you loaded has two types, integers and strings, stored in the array. You should load them using getInt() and getString(), and to solve the alternating key issue, just use mod. Here’s one way to do this with your code:

JSONObject json;

void setup() {
  json = loadJSONObject("data.json");
  JSONObject child = json.getJSONObject("facet_counts");
  JSONObject child2 = child.getJSONObject("facet_fields");
  JSONArray array = child2.getJSONArray("structHasAuthIdHal_fs");
  println(array.size());

  for (int i = 0; i< array.size(); i++) {
    if (i%2==0) {
      println(array.getString(i));
    } else {
      println(array.getInt(i));
    }
  }
  exit();
}

Also, try not to name things after common object names, like array for example, and try to keep your json properly indented to read.

2 Likes