Best Way to Rescursively Search JSON? #3469
-
I am currently working on a system to load assets listed inside of JSON files dynamically, which ideally does not know the overall structure of the JSON it receives. I'd like to recursively look through all levels of the JSON data to look for a specific key ("Asset") and perform the necessary loading based on the value. For example: main.json:
sub.json:
I have the capability to load other JSON files and process them once they are found, but finding all of the "Asset" keys is proving difficult. Ideally there would be some way to search through the JSON so that each of the JSON objects with key "Asset" could be found regardless of if it is inside an array or a subobject of a larger object. In general, the inner structure is known, i.e. every "Asset" object will have a "File", "Name", and "Type", but the outer structure is unknown: i.e., ["Assets"][0], ["Assets"][1], ["Layer"]["Asset"], etc. will not work. I've tried using the While efficiency is a bonus, I am not imagining the need for this to scale too large, so solutions which are slow yet easy to implement are welcomed! If there is nothing currently in the syntax for this, then I can imagine a way to do it, but I'd rather not reinvent the wheel if I can avoid it. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 11 replies
-
There's nothing in the API to do this for you. You'll have to iterate through objects/arrays yourself. There is {
"/Assets/0/Asset/File": "assets/music/Music.wav",
"/Assets/0/Asset/Name": "Music",
"/Assets/0/Asset/Type": 3,
"/Assets/1/Asset/File": "assets/images/Image.png",
"/Assets/1/Asset/Name": "Success",
"/Assets/1/Asset/Type": 1,
"/Layer/Asset/File": "assets/data/sub.json",
"/Layer/Asset/Name": "File",
"/Layer/Asset/Type": 0
} |
Beta Was this translation helpful? Give feedback.
-
You can do something like this: #include <nlohmann/json.hpp>
#include <iostream>
using json = nlohmann::json;
template<class UnaryFunction>
void recursive_iterate(const json& j, UnaryFunction f)
{
for(auto it = j.begin(); it != j.end(); ++it)
{
if (it->is_structured())
{
recursive_iterate(*it, f);
}
else
{
f(it);
}
}
}
int main()
{
json j = R"({
"Assets": [
{
"Asset": {
"File": "assets/music/Music.wav",
"Name": "Music",
"Type": 3
}
},
{
"Asset": {
"File": "assets/images/Image.png",
"Name": "Success",
"Type": 1
}
}
],
"Layer": {
"Asset": {
"File": "assets/data/sub.json",
"Name": "File",
"Type": 0
}
}
}
)"_json;
recursive_iterate(j, [](json::const_iterator it){
std::cout << it.key() << " : " << it.value() << std::endl;
});
} Output:
|
Beta Was this translation helpful? Give feedback.
You can do something like this: