json icon indicating copy to clipboard operation
json copied to clipboard

Update an existing struct

Open bitdivine opened this issue 3 years ago • 0 comments

It would be useful to be able to update just some parts of a structure. Example:

If I have:

Point {
  x: u32,
  y: u32,
}

I should be able to update an existing point without having to specify all the fields:

let mut point = Point { x:5, y: 7 };

update_point_with_json( point, "{\"x\": 5}" );

There is an existing serde method that deserializes into an existing struct, but in serde_json it aborts with an error if there are missing fields. If it could be told to ignore missing fields and just carry on, it seems as if maybe this could be achieved fairly easily. Here is a playground that demonstrates this: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bccf10311e413af139f3fee957a1e747

I am aware that there are full-blown json-patch implementations. One could convert an existing strict into JSON, apply a patch and concert back. That is quite heavyweight, where the usual point of deserializing into an existing struct is speed and low memory footprint. Also, I don't believe that JSON patch really belongs in serde; it is an operation on JSON that can live entirely outside serde. The same does not apply here, unless one goes with the inefficient "convert everything to JSON, merge, convert back" approach.

Are there people who would support such an "ignore missing, use existing value" update?

bitdivine avatar Apr 13 '22 08:04 bitdivine