PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How do I iterate over a JSON list? (rust)

 July 23, 2022     iterator, json, rust     No comments   

Issue

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"
        }
    ],

Solution

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)? {
    // ...
}


Answered By - cdhowie
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing