Home > Software design >  How do I iterate over a JSON list? (rust)
How do I iterate over a JSON list? (rust)

Time:07-20

I am loafing a gltf asset (basically a big json file). I want to iterate over one of the fields, i.e. I am doing this:

let data = fs::read_to_string("Assets/werewolf_animated.gltf").expect("Unable to read file");
    let json: serde_json::Value =
        serde_json::from_str(&data).expect("JSON was not well-formatted");

    for skin in json["skins"].into()
    {
        println!("{:?}", skin["inverseBindMatrices"]);
    }

But apparently rust cannot infer the type, I get:

 println!("{:?}", skin["inverseBindMatrices"]);
   |                          ^^^^ cannot infer type

How can I iterate over every entry in the skins json array?

For what is worth this is what the specific field looks like in the json file:

"skins" : [
        {
            "inverseBindMatrices" : 5,
            "joints" : [
                64,
                53,
                52,
                51,
                2,
            ],
            "name" : "Armature"
        }
    ],

CodePudding user response:

Value is an enum of all of the possible types of JSON values, so you have to handle the non-array cases as well (null values, booleans, numbers, strings, and objects). The helper Value::as_array() method returns an Option which is None in the non-array cases:

if let Some(skins) = json["skins"].as_array() {
    for skin in skins {
        // ...
    }
}

In this case, this is pretty much equivalent to:

if let serde_json::Value::Array(skins) = json["skins"] {
    for skin in skins {
        // ...
    }
}

If you want to signal an error via Result when this value isn't an array, you can combine Value::as_array() with Option::ok_or(). Here is an example, which assumes the presence of a custom error enum DataParseError:

for skin in json["skins"].as_array().ok_or(DataParseError::SkinsNotAnArray)? {
    // ...
}
  • Related