Ben Chuanlong Du's Blog

It is never too late to learn.

Parse YAML in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Comments

  1. The serde_yaml crate is the best tool for parsing YAML in Rust.
In [2]:
:sccache 1
:dep serde = ">=1.0.137"
:dep serde_yaml = ">=0.8.24"
Out[2]:
sccache: true
In [3]:
use std::fs
use std::collections::BTreeMap;
In [4]:
let mut map = BTreeMap::new();
map.insert("x".to_string(), 1.0);
map.insert("y".to_string(), f64::NAN);
map
Out[4]:
{"x": 1.0, "y": NaN}

Serialize the above BTreeMap to a YAML string.

In [5]:
let s = serde_yaml::to_string(&map).unwrap();
println!("{s}");
---
x: 1.0
y: .nan

Deserialize the above string back to a Rust type.

In [6]:
let deserialized_map: BTreeMap<String, f64> = serde_yaml::from_str(&s)?;
deserialized_map
Out[6]:
{"x": 1.0, "y": NaN}
In [24]:
let s = fs::read_to_string("tests.yaml").unwrap();
println!("{s}");
_11_highcard:
-   - 9d
    - 8d Ah 3c 2s 7h
    - 2c Kc Qc Jc Tc
    - .nan
-   - 2j
    - 8d Qs 3c 2s 7h
    - 2c Kc Qc Jc Tc
    - .nan
_11_other:
-   - Ac
    - 6d 5c 3c 2s 3j
    - Qc Jh Td 9d 2j
    - .nan
-   - 2j
    - 8d 6h 5c 4s 7h
    - 2c Kc Qc Jc Tc
    - .nan
_11_pair:
-   - Ac
    - Td 5c 3c 2s Th
    - Qc Jh Ts 9d 2j
    - .nan
-   - Ac
    - 5d 5c 3c 2s Th
    - Qc Jh Ts 9d 2j
    - .nan
In [25]:
let deserialized_map: BTreeMap<String, Vec<(String, String, String, f64)>> = serde_yaml::from_str(&s).unwrap();
deserialized_map
Out[25]:
{"_11_highcard": [("9d", "8d Ah 3c 2s 7h", "2c Kc Qc Jc Tc", NaN), ("2j", "8d Qs 3c 2s 7h", "2c Kc Qc Jc Tc", NaN)], "_11_other": [("Ac", "6d 5c 3c 2s 3j", "Qc Jh Td 9d 2j", NaN), ("2j", "8d 6h 5c 4s 7h", "2c Kc Qc Jc Tc", NaN)], "_11_pair": [("Ac", "Td 5c 3c 2s Th", "Qc Jh Ts 9d 2j", NaN), ("Ac", "5d 5c 3c 2s Th", "Qc Jh Ts 9d 2j", NaN)]}
In [16]:
let s = serde_yaml::to_string(&deserialized_map).unwrap();
println!("{s}");
---
_11_highcard:
  - - 9d
    - 8d Ah 3c 2s 7h
    - 2c Kc Qc Jc Tc
    - .nan
  - - 2j
    - 8d Qs 3c 2s 7h
    - 2c Kc Qc Jc Tc
    - .nan
_11_other:
  - - Ac
    - 6d 5c 3c 2s 3j
    - Qc Jh Td 9d 2j
    - .nan
  - - 2j
    - 8d 6h 5c 4s 7h
    - 2c Kc Qc Jc Tc
    - .nan
_11_pair:
  - - Ac
    - Td 5c 3c 2s Th
    - Qc Jh Ts 9d 2j
    - .nan
  - - Ac
    - 5d 5c 3c 2s Th
    - Qc Jh Ts 9d 2j
    - .nan

In [26]:
use std::fs::File;
use std::io::{BufWriter, Write};
let f = File::create("out.yaml").expect("Unable to create the file out.yaml");
let mut bw = BufWriter::new(f);
serde_yaml::to_writer(bw, &deserialized_map).unwrap();

References

In [ ]:

Comments