json icon indicating copy to clipboard operation
json copied to clipboard

Convert Value to String in one line

Open hniksic opened this issue 3 years ago • 2 comments
trafficstars

Is there a convenience method to convert owned value to owned String, like an owned version of as_str(). For example:

let v: Value = json!("foo"); // in my case some_map.remove(some_key)
let s: String = v.try_into().unwrap();

The above doesn't compile, and there is no Value::into_string() or similar. As far as I can tell, the only way to extract the string is by matching:

let s = match v {
    Value::String(s) => s,
    _ => panic!("expected String"),
};

I need this kind of thing fairly often and I wonder if there's a more succinct way to write the above. Of course, I can write a utility function that does it, but would prefer to use a standard API offered by the crate if possible.

hniksic avatar Dec 01 '21 14:12 hniksic

This is implemented in #947. You can check in dtolnay's unholy triage list when he finally gets around reviewing it [man please allow more maintainers to join :sob:]

kangalio avatar May 23 '23 17:05 kangalio

I would prefer a dedicated into_string() rather than the try_into().

conradludgate avatar May 23 '23 17:05 conradludgate