Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter by value #1708

Closed
metingul opened this issue Feb 8, 2022 · 2 comments
Closed

Filter by value #1708

metingul opened this issue Feb 8, 2022 · 2 comments
Labels
question v6 ArduinoJson 6

Comments

@metingul
Copy link

metingul commented Feb 8, 2022

Hello,
I want to filter result by value (like database query), the sample json content below. for example I want to get userID for ESP8266 (I know userName but I want to fetch userID for that value.)

thank you.

[
  {
    "userID": 1,
    "userName": "Arduino",
    "eMail": "arduino@arduinojson.org"
  },
  {
    "userID": 2,
    "userName": "ESP8266",
    "eMail": "esp@arduinojson.org"
  },
  {
    "userID": 3,
    "userName": "ESP32",
    "eMail": "esp32@arduinojson.org"
  }
]
@metingul
Copy link
Author

metingul commented Feb 8, 2022

I solved the problem with code below; but may be there is easyway method / function.

char* input = "[{\"userID\":1,\"userName\":\"Arduino\",\"eMail\":\"arduino@arduinojson.org\"},{\"userID\":2,\"userName\":\"ESP8266\",\"eMail\":\"esp@arduinojson.org\"},{\"userID\":3,\"userName\":\"ESP32\",\"eMail\":\"esp32@arduinojson.org\"}]";
// size_t inputLength; (optional)

StaticJsonDocument<256> doc;

DeserializationError error = deserializeJson(doc, input);

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

for (JsonObject item : doc.as<JsonArray>()) {

  int userID = item["userID"]; // 1, 2, 3
  String userName = item["userName"]; // "Arduino", "ESP8266", "ESP32"
  const char* eMail = item["eMail"]; // "arduino@arduinojson.org", "esp@arduinojson.org", ...

  if (userName == "ESP8266") {
  Serial.print("UserID Found:");
  Serial.println(userID);    
  }

}

@bblanchon
Copy link
Owner

Hi @metingul,

Enumerating the objects in the objects is the way to go.

You could avoid a copy by using a JsonString instead of a String (requires ArduinoJson 6.19).

Best regards,
Benoit

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 17, 2022
@bblanchon bblanchon added the v6 ArduinoJson 6 label Feb 6, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
question v6 ArduinoJson 6
Projects
None yet
Development

No branches or pull requests

2 participants