Extracting array from JSON element

I'm trying to wrap my head around how to extract an array from a JSON element. In the case of the below JSON, I'm trying to access the "values" key.

{"act":"D8755ABF713C","id":4,"typ":4,"tank":2,"ip":"192.168.249.99","values":[0,1]}

Anyone have a clear way of accessing these elements? I've followed the deserialization tutorial for ArduinoJson6, but got lost in the process.

Hello,

Look this tutorial : ESP8266: Parsing JSON Arrays - techtutorialsx

I followed this tutorial and it won't compile. I'm using the ArduinoJson6 library and that might be part of the issue.

After you deserialize into 'doc', doc["values"][0] would get you the first (0) and doc["values"][1] would get you the second (1).

See the ArduinoJson Assistant:

Tell it you want to deserialize and paste in your JSON. It will write some code for you:

// const char* input;
// size_t inputLength; (optional)

StaticJsonDocument<192> doc;

DeserializationError error = deserializeJson(doc, input, inputLength);

if (error) {
  Serial.print(F("deserializeJson() failed: "));
  Serial.println(error.f_str());
  return;
}

const char* act = doc["act"]; // "D8755ABF713C"
int id = doc["id"]; // 4
int typ = doc["typ"]; // 4
int tank = doc["tank"]; // 2
const char* ip = doc["ip"]; // "192.168.249.99"

int values_0 = doc["values"][0]; // 0
int values_1 = doc["values"][1]; // 1

If you want the data in an array, you can replace that last bit with:

int values[2];
values[0] = doc["values"][0]; // 0
values[1] = doc["values"][1]; // 1

For larger arrays:

int values[N];
  for (size_t i=0; i < N; i++)
    values[i] = doc["values"][i];
1 Like

This would fine if the number of values was fixed. Sometimes it is 1. Sometimes 4.

Figured it out.

JSonArray values=inbound['values'];
and then roll through it with

for(int i=0;i<values.size();i++) {
// Access elements here....
}

Perhaps you would have gotten better results if you had mentioned in your post that the the size of "values" varied.

size_t N = inbound["values"].size();
int values[N];
  for (size_t i=0; i < N; i++)
    values[i] = inbound["values"][i];

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.