Return json keys from deserialized Object

#1

I’m trying to deserialize a JSON file in which some field keys will be variable and of hundreds or even thousands of possibilities that could change frequently. I need the keys and their values in order to perform some operation. serde_json makes it simple to get the values from a deserialized object if the key is known, but I will not know the keys ahead of time.

Object({"known_key": Object({<variable number of fields with unknown and unpredictable names/values})})
#2

By “frequently” what do you mean? 10 times a second? Or twice every 3 minutes? If the latter applies then a file watcher would work well like notify.


Or maybe I misinterpreted your question and are looking for a quick way to extract keys from the deserialized object?

#3

No, I mean the list of possible field names is constantly evolving, but the particular file I am trying to read will not change that often.

#4

for (name, value) in serde_json::Value::as_object().unwrap().iter() should work.


Ie:

use serde_json::{Value, Map};
let val: Value = //Deserialize here
for (name, obj) in val["known_key"].as_object().unwrap().iter() {
    println!("{} is {:?}", name, obj);
}
2 Likes
#5

Man that is much simpler than I was making it. Thanks.

1 Like