Help with a simple structured YAML file

Hi all,

I'm trying to deserialize a simple YAML , but I'm stumbling upon some weird behaviors I can't understand.

This is my YAML file:

---
actors:
  - deniro:
      name: "Robert de Niro"
      kind: actor
      movies: ["Taxi Driver", "Heat", "The intern"]
  - pacino:
      name: "Al Pacino"
      kind: actor
      movies: ["The godfather I", "The godfather II", "Serpico"]
  - palma:
      name: "Brian de Palma"
      kind: director
      movies: ["Carrie", "Scarface", "Body Double"]
...

Work perfectly with Ruby.

With serde_yaml, I've defined the following structures:

#[derive(Debug, Deserialize)]
struct MyYaml {
    actors: Vec<Actor>,
}

#[derive(Debug, Deserialize)]
struct Actor {
    name: String,
    kind: String,
    movies: Vec<String>,
}

When deserializing:

thread 'main' panicked at 'unable to load: Message("missing field `name`", Some(Pos { marker: Marker { index: 22, line: 3, col: 10 }, path: "actors[0]" }))', src/main.rs:21:16
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

But if I delete indentation from fields (name, kind movies) like this:

---
actors:
  - deniro:
    name: "Robert de Niro"
    kind: actor
    movies: ["Taxi Driver", "Heat", "The intern"]
  - pacino:
    name: "Al Pacino"
    kind: actor
    movies: ["The godfather I", "The godfather II", "Serpico"]
  - palma:
    name: "Brian de Palma"
    kind: director
    movies: ["Carrie", "Scarface", "Body Double"]
...

it works:

MyYaml {
    actors: [
        Actor {
            name: "Robert de Niro",
            kind: "actor",
            movies: [
                "Taxi Driver",
                "Heat",
                "The intern",
            ],
        },
        Actor {
            name: "Al Pacino",
            kind: "actor",
            movies: [
                "The godfather I",
                "The godfather II",
                "Serpico",
            ],
        },
        Actor {
            name: "Brian de Palma",
            kind: "director",
            movies: [
                "Carrie",
                "Scarface",
                "Body Double",
            ],
        },
    ],

The first version identation is perfectly valid, but not read. Any hint ?

Also, how to store the name of the structure like deniro:, pacino: or palma: ?

Thanks a lot for your help.

Your YAML isn't an array, but a map. Instead of Vec<Actor> it maps to HashMap<String, Actor>.

Actually it's Vec<HashMap<String, Actor>> where each hashmap has only one entry.

1 Like

Oh my mistake :wink:

Thanks for pointing this immediately !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.