How to get key name instead of value with serde json

This is the JSON I'm parsing: https://pastebin.com/4k67XbNW

And following is the code I'm currently using, but there must be a better way... right?

let first = &json["players"]["0"]["characters"];
if let Object(first) = first {
    replay.characters[0] = Some(first.keys().nth(0).unwrap().to_string());
}
let second = &json["players"]["1"]["characters"];
if let Object(second) = second {
    replay.characters[1] = Some(second.keys().nth(0).unwrap().to_string());
}
etc...

The pastebin you posted isn't JSON; I'm assuming it's the parsed Rust values?

Not sure why you want the key instead of the value - if it's to not have to hardcode each player separately, you can iterate over json["players"]:

let chars = json["players"]
    .iter()
    .filter_map(|(key, val)| {
        let player_id = key.parse::<usize>().ok()?;
        let char_id = val["characters"]?.keys().nth(0)?.to_string();
        Some((player_id, char_id))
    });

for (player_id, char_id) in chars {
    replay.characters[player_id] = Some(char_id);
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.