Looking for a tutorial on loading, modifying and saving json with json_serde and strict type


I'm coming from a python background. I am trying to port my python project to Rust
And what I want to do is load a nested json from a url. Use json_serde with strict typing and tagging.
Modify the fields, data, sub documents and save the json.
Getting lot of errors here or there...or there there...
I can't seem to find any tutorials on it.

There are a few examples here.

Good example but almost !
They load json, but then create new structs. I would like to modify some of the data from the json instead of recreating it

Can you post what you have tried?


Ok, Here is an example of trying to set just one field but then can't use it after.

Ah, I understand where the issue is. If you want to using unwrap and get the field inside an Option, then you must use .as_mut() rather than just write &mut.

println!("{:?}", data.address);
let mut m =  data.address.as_mut().unwrap(); 
m.street = "ok".to_string();

This works because the .as_mut() method takes an &mut Option<T> and returns an Option<&mut T>. The call to unwrap will then give you the inner value, which is &mut T.

As an alternative to this, you could use a match statement on the Option, but that's more verbose.


I just rearranged the lines to appease the compiler.

@Rustaceous That doesn't solve the issue. The problem is that when using an .unwrap() in this manner without an .as_mut(), it will consume the thing it is called on. Your example compiles because you don't use data after you destroyed it, but if you didn't want to destroy data, then it doesn't solve the problem.

ty Alice. It worked !
Now to study it..

Good one Rustaceous...lol

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.