I am using ArduinoJson and ESP8266HTTPClient.
Say I have a DynamicJsonDocument that has an unknown number of entries with information on different persons:
[
{
"ID": "12345",
"name": "John Smith",
"Address": "Street 1"
},
.
.
.
{
"ID": "00345",
"name": "Paul Anderson",
"Address": "Street 2"
}
]
I would like to somehow store the values associated with the key "name" for all the different persons. For example, have something like:
String name1 = "";
...
String nameN = "";
.
.
.
Serial.println(name1);
...
Serial.println(nameN);
To print a list of all the names:
John Smith
Paul Anderson
The only information of the JSON I have beforehand is the keys each entry will have. I do not know how many entries there will be.
How can I go about this?
EDIT: Why I want to do this:
I am using the ESP as a client to get information from a server in the form of a JSON similar to what I wrote above. At the same time, I am serving a simple HTML website by doing server.send(200, "text/html", HTML_code);
using the ESP as an AP. I was able to just cram the whole JSON into the HTML as text, but I would like to just have specific information from the JSON, as explained above.
I am aware what I am doing is far from elegant or the "correct way to do it", but I am learning all of this, so any criticism and help is more than welcome :)
1 Answer 1
Directly from the ArduinoJson Assistant:
// Stream& input;
StaticJsonDocument<384> doc;
deserializeJson(doc, input);
for (JsonObject elem : doc.as<JsonArray>()) {
const char* ID = elem["ID"]; // "12345", "13244", "00345"
const char* name = elem["name"]; // "John Smith", "Jason Statham", "Paul Anderson"
const char* Address = elem["Address"]; // "Street 1", "Street 2", "Street 3"
}
See also:
-
Thank you, I will try this. How would I access for example "Jason Statham" inside the "name" char*?choreley– choreley2021年02月02日 15:16:01 +00:00Commented Feb 2, 2021 at 15:16
-
Serial.println(name); // prints "Jason Statham"
Benoit Blanchon– Benoit Blanchon2021年02月02日 16:01:24 +00:00Commented Feb 2, 2021 at 16:01 -
Wouldn't that print all the names and not a specific one?choreley– choreley2021年02月02日 16:11:12 +00:00Commented Feb 2, 2021 at 16:11
JsonArray::size()
so just iterate over the array getting each object in turn. It's also recommended to use iterators instead of a for loop.<html><header>...</header><body>
then iterate the JSON<div> put name here </div>
, then serve</body></html>
strstr(json, "\"key\"")
and thenstrchr(thatString, ',')
to get the span from that key's starting point. You could use String methods too, but those tend to cause problems if over-used.