Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serde_yaml::Value -> serde_json::Value, `null` keys

I have big complex YAML file, which I successfully read into serde_yaml::Value and need to send to the user (from Axum handler) as JSON.

But somewhere deep inside that big YAML there are keys like null. And serde_json::json! panics with message "key must be a string".

I understand that this is valid case for YAML, but not valid for JSON.
But is there some workaround for that? I just need string keys like "null" in place of those nulls.

JavaScript and Go YAML parsers behaves exactly like this...

I wrote a big recursive function for that, which manually converts values, but maybe this is overkill. And also my function somehow breaks YAML merges (<<), don't know why yet.

like image 638
yumaa Avatar asked Oct 19 '25 02:10

yumaa


1 Answers

You can simply deserialize the yaml into a serde_json::Value instead, that way it's guaranteed to be serializable to json later:

fn main() {
    let yaml: serde_json::Value = serde_yaml::from_str(r#"null: "hello""#).unwrap();
    let json_str = serde_json::to_string(&yaml).unwrap();
    println!("{json_str}");
}

output:

{"null":"hello"}

Playground

like image 101
cafce25 Avatar answered Oct 22 '25 05:10

cafce25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!