如何从serde_yaml :: Value获取嵌套属性?

时间:2019-06-25 13:31:44

标签: rust yaml serde

我有以下YAML文件

version: '3'
indexed:
  file1: "abc"
  file2: "def"
  file3: 33

我是用以下代码阅读的:

pub fn read_conf() -> Result<(), Box<dyn Error>>{
    let f = File::open(".\\src\\conf.yaml")?;
    let d: Mapping = from_reader(f)?;
    let value = d.get(&Value::String("version".into())).unwrap();
    println!("{:?}", value.as_str().unwrap());

    let value = d.get(&Value::String("indexed.file1".into())).unwrap();
    println!("{:?}", value);
    Ok(())
}

产生

"3"
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src\libcore\option.rs:345:21

如何实例化Value以获得所需的值?

1 个答案:

答案 0 :(得分:1)

使用链接索引语法:

use serde_yaml::Value; // 0.8.9

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = r#"
    version: '3'
    indexed:
      file1: "abc"
      file2: "def"
      file3: 33
    "#;

    let d: Value = serde_yaml::from_str(input)?;

    let f1 = &d["indexed"]["file1"];
    println!("{:?}", f1);

    Ok(())
}

或者更好的是,为类型派生Deserialize并让它完成艰苦的工作:

use serde::Deserialize; // 1.0.93
use serde_yaml; // 0.8.9
use std::collections::BTreeMap;

#[derive(Debug, Deserialize)]
struct File {
    version: String,
    indexed: BTreeMap<String, String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = r#"
    version: '3'
    indexed:
      file1: "abc"
      file2: "def"
      file3: 33
    "#;

    let file: File = serde_yaml::from_str(input)?;
    let f1 = &file.indexed["file1"];

    println!("{:?}", f1);

    Ok(())
}

另请参阅: