How To: Query for all values of a given Key within an array #329
-
Given:
How could you use json_query (or some other querying-like function) to fetch the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
With JSONPath, like this: #include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpath/jsonpath.hpp>
using jsoncons::json;
namespace jsonpath = jsoncons::jsonpath;
int main()
{
json root = json::parse(R"(
{
"arr":[
{
"keyOfInterest":true,
"keyOfInsignificants":true
},
{
"keyOfInterest":false,
"keyOfInsignificants":true
},
{
"keyOfInterest":true,
"keyOfInsignificants":true
}
]
}
)");
auto results = jsonpath::json_query(root, "$.arr[*]['keyOfInterest']");
std::cout << results << "\n";
} Output: [true,false,true] You can think of a JSONPath expression in terms of its left hand side and its right hand side, its right hand side is applied to each element produced by its left hand side. So in the expression
Note that each element in the result - {"0":true, "1":false, "2":true} with a JSONPath expression, you can only select a collection of elements that are already in the JSON document. |
Beta Was this translation helpful? Give feedback.
-
Or using JMESPath: #include <jsoncons/json.hpp>
#include <jsoncons_ext/jmespath/jmespath.hpp>
using jsoncons::json;
namespace jmespath = jsoncons::jmespath;
int main()
{
json root = json::parse(R"(
{
"arr":[
{
"keyOfInterest":true,
"keyOfInsignificants":true
},
{
"keyOfInterest":false,
"keyOfInsignificants":true
},
{
"keyOfInterest":true,
"keyOfInsignificants":true
}
]
}
)");
try
{
auto result1 = jmespath::search(root, "arr[*].\"keyOfInterest\"");
std::cout << "(1) " << result1 << "\n";
auto result2 = jmespath::search(root, "arr[*].{\"Key of Interest\" : \"keyOfInterest\"}");
std::cout << "(2) " << result2 << "\n";
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
} Output: (1) [true,false,true]
(2) [{"Key of Interest":true},{"Key of Interest":false},{"Key of Interest":true}] Note that, unlike JSONPath, JMESPath has some capabilities for producing elements that are not in the original JSON document. |
Beta Was this translation helpful? Give feedback.
Or using JMESPath: