Recursive AI

Convert YAML to JSON and back

All oneyaml Rust recipes

Turn a YAML file into JSON, or JSON into YAML. oneyaml’s serde_json feature converts between oneyaml::Value and serde_json::Value.

Terminal
cargo add [email protected] -F serde_json
cargo add serde_json
RUST
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(())
}
Text
{
  "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, .nan and .inf, integers beyond 64 bits, and nesting past 128 levels. Value::to_json_with lists them all.
  • The JSON keys above come out sorted because serde_json::Value sorts them by default. Turn on serde_json’s preserve_order feature to keep the file’s order.
  • JSON is valid YAML 1.2, so oneyaml::from_str reads JSON text directly. The YAML written uses block style.
  • For typed data, skip Value: read into your struct with oneyaml::from_str and write it with serde_json::to_string.