Serde & pointer_mut

In this sample: Value in serde_json::value - Rust

*value.pointer_mut("/x").unwrap() = ...

will bomb if there is no value under /x already. How do I assign a new value then?

x could be an array, for instance, if /x/0 is not assigned, how do I assign it? I would need to add an item to the array, I guess.

And other question. Serde also seems to have a problem with types, if x has a value that is i32 and then I try to assign a value that is a string, using pointer_mut, it's going to complain. In JavaScript anything goes. I guess I could "take" the value and assign the new one but I am back to the first question.

TIA

Thanks

I'd probably get the parent node of x, treat it as a JSON object and use the API that serde_json provides for it:

fn main() {
    let mut value = serde_json::json!({
        "some_key": {},
    });

    value
        .pointer_mut("/some_key")
        .unwrap()
        .as_object_mut()
        .unwrap()
        .insert("x".to_owned(), "whatever value you want to assign".into());
}

Playground.

That being said, I wouldn't necessarily use Value in the first place, if I could avoid doing so. Working with a dynamically typed data representation such as JSON in a strongly typed language like Rust, you'll inevitably have to deal with a lot more verbosity. So if possible, I would parse the JSON object at hand into native types before modifying those instead.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.