如何解析包含简单列表和键值列表(关联数组)的 YAML [英] how to parse a YAML containing a simple list together with a key-value list (associative array)
本文介绍了如何解析包含简单列表和键值列表(关联数组)的 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 YAML:
build:
- step 1
- step 2
- name: step 3
do: something
- name: step 4
get: fetch ...
- name: step 5
put: upload something
为了解析它,我正在尝试
And for parsing it I am trying with this
#[derive(Debug, Deserialize, PartialEq)]
struct Config {
build: Option<Vec<Steps>>
}
#[derive(Debug, Deserialize, PartialEq)]
struct Build {
#[serde(flatten)]
item: String,
steps: Steps,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Steps {
name: String,
r#do: Option<String>,
put: Option<String>,
get: Option<String>,
}
但我收到此错误:
Error parsing configuration file: build[0]: invalid type: string "step 1", expected struct Build
我只能解析:
build:
- step 1
- step 2
使用:
#[derive(Debug, Deserialize, PartialEq)]
struct Config {
build: Option<Vec<String>>
}
或者:
build:
- name: step 1
do: foo
- name: step 2
do: bar
使用:
#[derive(Debug, Deserialize, PartialEq)]
struct Config {
build: Option<Vec<Steps>>
}
但是找不到同时拥有这两个选项的方法,您知道如何解析吗?
But can't find a way to have both options, any idea about how could this be parsed?
推荐答案
使用枚举:
#[derive(Debug, serde::Deserialize, PartialEq)]
struct Build {
build: Vec<Foo>,
}
#[derive(Debug, serde::Deserialize, PartialEq)]
#[serde(untagged)]
enum Foo {
Step(Step),
Bar(String),
}
#[derive(Debug, serde::Deserialize, PartialEq)]
struct Step {
name: String,
#[serde(rename = "do")]
make: Option<String>,
put: Option<String>,
get: Option<String>,
}
fn main() -> Result<(), serde_yaml::Error> {
let input = r#"build:
- step 1
- step 2
- name: step 3
do: something
- name: step 4
get: fetch ...
- name: step 5
put: upload something"#;
let build: Build = serde_yaml::from_str(input)?;
println!("{:#?}", build);
Ok(())
}
这篇关于如何解析包含简单列表和键值列表(关联数组)的 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文