4

I'm trying to parse this YAML file

application:
  build: something
  container_name: another_thing
  environment:
    - ONE_ENV=fake
    - SEC_ENV=something

I've created this code that works perfectly:

#[macro_use]
extern crate serde_derive;
extern crate serde_yaml;

use std::fs::File;
use std::io::Read;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Application {
    application: Data,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Data {
    build: String,
    container_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    environment: Option<Vec<String>>,
}

fn main() {
    let filename = "example.yml";
    match File::open(filename) {
        Ok(mut file) => {
            let mut content = String::new();
            file.read_to_string(&mut content).unwrap();

            let application_data: Application = serde_yaml::from_str(&content).unwrap();
            println!("{:?}", application_data.application.environment);
        }
        Err(error) => {
            println!("There is an error {}: {}", filename, error);
        }
    }
}

I need to support this format too:

application:
  build: something
  container_name: another_thing
  environment:
    ONE_ENV: fake
    SEC_ENV: something

How I can deal with two different ways to parse?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Horacio
  • 2,865
  • 1
  • 14
  • 24
  • Have you [read the Serde documentation](https://serde.rs/string-or-struct.html)? – Shepmaster Mar 19 '19 at 16:45
  • 5
    [The duplicates applied to your question (using JSON)](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=57c5990c3595c0a740138dcb4e0daa4c). TL;DR: create an [untagged enum](https://serde.rs/enum-representations.html#untagged): `#[serde(untagged)] enum Environment { Vec(Vec), Hash(BTreeMap) }` and use that for your `environment`. – Shepmaster Mar 19 '19 at 16:59
  • Thank you @Shepmaster the second helps me a lot, and the documentation it's how I started, but Enum approach is much better. Thanks you – Horacio Mar 20 '19 at 10:41

0 Answers0