bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.72k stars 1.12k forks source link

How to access each JsonObject's key #755

Closed nathanRamaNoodles closed 6 years ago

nathanRamaNoodles commented 6 years ago

So this issue is derived from issue 226 Here is the json string:

[
  {
    "Store": "Toysrus",
    "Status": "closing",
    "toys": ["Nintendo Switch", "Hockey Gear", "pogo stick"]
  },
 {
    "Name": "Bob",
    "Job": "Car Dealer",
    "cars": ["Toyota", "Honda", "BMW"]
  }
]

When I try to access a JsonObject's key with this:

const char* json = "[{\"Store\":\"Toysrus\",\"Status\":\"closing\",\"toys\":[\"Nintendo Switch\",\"Hockey Gear\",\"pogo stick\"]},{\"Name\":\"Bob\",\"Job\":\"Car Dealer\",\"cars\":[\"Toyota\",\"Honda\",\"BMW\"]}]";

const size_t bufferSize = JSON_ARRAY_SIZE(2) + 2*JSON_ARRAY_SIZE(3) + 2*JSON_OBJECT_SIZE(3) + 140;
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonArray& root= jsonBuffer.parseArray(json);
JsonObject& stuff = root[0];
const char* keyName = stuff [0].begin()->key; // "Store"
const char* keyName1 = stuff [1].begin()->key; // "Status"
const char* keyName2 = stuff [2].begin()->key; // "toys"
Serial.println("Yo, the mysterious key names are");
Serial.println(keyName);Serial.println(keyName1);Serial.println(keyName2);

I get a compile error saying, 'class ArduinoJson::Internals::JsonObjectSubscript<const int&>' has no member named 'begin'

My project requires me to use numbers because the key names will be different every time.

So this is the end goal:

Yo, the mysterious key names are
Store
Status
toys

By the way, thanks for this amazing library.

bblanchon commented 6 years ago

Hi @nathanRamaNoodles,

It looks to me that you simply need to iterate over each key-value pair in JsonObject& stuff. Please have a look at: JsonObject::begin() / JsonObject::end().

Regards, Benoit