-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Function to resolve a JSON path composed of several keys #1505
Comments
Hi @sorokolokarim, It looks like you want something like this: template<typename T>
T value(const char* json, const char* key)
{
DynamicJsonDocument doc(4096);
deserializeJson(doc, json);
return doc[key].as<T>();
}
const char data[] = R"=({"x1":"1","x2":"2"})=";
int8_t x = value<int8_t>(data, "x2"); This function works with all types except Best regards, |
Online demo: https://wandbox.org/permlink/0Un6VcidHMhDBRx6 |
@bblanchon Question -> Is there a method that can give me the possibility from a function to insert an indefinite number of parameter and that then I will use to retrieve a value or values from the json document? Example : (something like this) template<typename T>
T value(const char* json, const char* key, ...)
{
DynamicJsonDocument doc(4096);
deserializeJson(doc, json);
return doc[key][...].as<T>();
} const char data[] = R"=( {"a": {"b": {"x2": 2}}})=";
expected result 1 :
int8_t x = value<int8_t>(data, "c", "d"); // 5
expected result 2 :
int8_t x = value<int8_t>(data, "a", "b", "x2"); // 2 I'm still a beginner and I have a hard time doing something like this. Thank you very much for the helping hand. |
Hi @sorokolokarim, Doing so require a recursive function with a template parameter pack, like so: template <typename Key>
JsonVariantConst resolvePath(JsonVariantConst variant, Key key) {
return variant[key];
}
template <typename Key, typename... Tail>
JsonVariantConst resolvePath(JsonVariantConst variant, Key key, Tail... tail) {
return resolvePath(variant[key], tail...);
}
template <typename T, typename... Keys>
T value(const char* json, Keys... keys) {
DynamicJsonDocument doc(4096);
deserializeJson(doc, json);
return resolvePath(doc, keys...).template as<T>();
}
const char data[] = R"=( {"a": {"b": {"x2": 2}}})=";
int8_t x = value<int8_t>(data, "a", "b", "x2"); // 2 I know this looks complicated, but it is a common pattern. Demo: https://wandbox.org/permlink/PgICTZ1nIjAULTKO Best regards, |
Hi @bblanchon 🥇 |
I want to deserialize and get value by this way but it doesn't work.
int8_t x = value(data, jsonDoc, jsonDoc["x2"].to< JsonVariant >());
Serial.print("x : "); Serial.println(x);
// Output x : 1
Question 1 -> Why Output (x) = 1 and not 2
Question 2 -> How to do to have Output (x) = 2
Very very good library, thank you !
Sorry for my english, i speak french
The text was updated successfully, but these errors were encountered: