Turn a YAML file into JSON, or JSON into YAML. oneyaml’s serde_json feature converts between oneyaml::Value and serde_json::Value.
cargo add [email protected] -F serde_json cargo add serde_json
use oneyaml::Value; fn main() -> Result<(), Box<dyn std::error::Error>> { // YAML to JSON: read a Value, convert it (feature "serde_json"). let yaml = "\ name: web ports: [80, 443] tls: true owner: ~ "; let v: Value = oneyaml::from_str(yaml)?; let json = serde_json::Value::try_from(&v)?; println!("{}", serde_json::to_string_pretty(&json)?); // JSON to YAML: JSON is valid YAML 1.2, so read it and write YAML. let text = r#"{"name": "web", "ports": [80, 443], "env": {"LOG": "info"}}"#; let v: Value = oneyaml::from_str(text)?; print!("{}", oneyaml::to_string(&v)?); // Values with no JSON form are an error with a path, not a silent change. let v: Value = oneyaml::from_str("ratio: .nan\n")?; println!("{}", serde_json::Value::try_from(&v).unwrap_err()); Ok(()) }
{ "name": "web", "owner": null, "ports": [ 80, 443 ], "tls": true } name: web ports: - 80 - 443 env: LOG: info float .nan has no JSON form (JSON numbers are finite) at ratio
Good to know
- No silent coercion. What JSON can’t hold is an error with its path: tags, non-string keys,
.nanand.inf, integers beyond 64 bits, and nesting past 128 levels.Value::to_json_withlists them all. - The JSON keys above come out sorted because
serde_json::Valuesorts them by default. Turn onserde_json’spreserve_orderfeature to keep the file’s order. - JSON is valid YAML 1.2, so
oneyaml::from_strreads JSON text directly. The YAML written uses block style. - For typed data, skip
Value: read into your struct withoneyaml::from_strand write it withserde_json::to_string.