Search code examples
jsonrustserdeserde-json

How to modify a string inside a serde_json::Value::String?


I have a serde_json::Value containing a string that I want to modify, if possible without cloning the string. I would imagine you would do it like this:

let mut value = Value::String("Hello world".to_string());
let mut string = value.as_mut_string().unwrap();
string.push('!');

But there is no such thing as as_mut_string. I could do this:

let mut value = Value::String("Hello world".to_string());
let mut string = value.as_str().unwrap().to_string();
string.push('!');
value = Value::String(string);

However, this is both ugly code and inefficient since I have to clone the string. Is there a better solution?


Solution

  • serde_json::value::Value is an enum, you can just pattern match it:

    let mut value = Value::String("Hello world".to_string());
    if let Value::String(string) = &mut value {
        string.push('!');
    }
    
    println!("{:?}", value);
    

    (Permalink to the playground)