←back to thread

JSON Patch

(zuplo.com)
299 points DataOverload | 1 comments | | HN request time: 0.205s | source
Show context
skrebbel ◴[] No.41881933[source]
I quite like JSON Patch but I've always felt that it's so convoluted only because of its goal of being able to modify every possible JSON document under the sun. If you allow yourself to restrict your data set slightly, you can patch documents much simpler.

For example, Firebase doesn't let you store null values. Instead, for Firebase, setting something to null means the same as deleting it. With a single simple restriction like that, you can implement PATCH simply by accepting a (recursive) partial object of whatever that endpoint. Eg if /books/1 has

    { title: "Dune", score: 9 }
you can add a PATCH /books/1 that takes eg

    { score: null, author: "Frank Herbert" }
and the result will be

    { title: "Dune", author: "Frank Herbert" }
This is way simpler than JSON Patch - there's nothing new to learn, except "null means delete". IMO "nothing new to learn" is a fantastic feature for an API to have.

Of course, if you can't reserve a magic value to mean "delete" then you can't do this. Also, appending things to arrays etc can't be done elegantly (but partially mutating arrays in PATCH is, I'd wager, often bad API design anyway). But it solves a very large % of the use cases JSON Patch is designed for in a, in my humble opinion, much more elegant way.

replies(7): >>41882045 #>>41882475 #>>41883360 #>>41886201 #>>41886934 #>>41887163 #>>41887172 #
ndr ◴[] No.41887172[source]
How does it handle arrays/repeated fields?

Eg: how do you update a field of the third element on an array when there are 5 elements in an array?

The same that in `jq` would be:

`jq ".people[2].age |= 50" example.json`

replies(1): >>41887471 #
bpicolo ◴[] No.41887471[source]
You overwrite the entire array. Replacement is a safe, idempotent operation.

If you're concerned about concurrency for array updates, you'll usually need a form of concurrency control whether the database supports partial updates or not.

replies(1): >>41904589 #
1. account42 ◴[] No.41904589[source]
Unless your array is only a relatively small part of the file this defeats the purpose of patching. And yes, concurrency is also an issue in simple cases (e.g. append/prepend) that json patch handles fine on its own.