Search code examples
rustserializationserdeserde-json

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.


Solution

  • 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