JSON Patch is a neat idea for describing changes to JSON -
... the idea is that you can clean-up muddled parts of a codebase, by making data-things explicit.
it is pretty simple, and sort of beautiful.
Does the world need another json-patch implementation? no.
did I make one, and is it crappy? yes.
import { get, make, apply } = from 'garbage-patch'
let json = {
foo: ['bar', 'baz'],
}
// apply clean changes to the json
let patch = { op: 'add', path: '/foo/-', value: 'bob' }
apply(patch, json)
/* {
foo: ['bar', 'baz', 'bob'],
} */
// make a valid json pointer
let ptr = make(['foo', 1])
// '/foo/1'
// use it to get some data
let result = get(ptr, json)
// 'baz'
there is nothing too-clever going on. the min.js build is 2.5kb.
these methods take inspiration from the pointer spec and the patch-spec but have some differences:
-
get() is more-forgiving
if you give it a path '/foo/typo/9/wrong' that doesn't exist,
it will just say - 'haha! no problem! undefined! ✌'also, a trailing slash is allowed -
/foo/
also, a leading slash is optional -
foo/1
if you prefer, you can use an array as a pointer, too:
let json = { foo: [null, 'found'] }
let found = get(['foo', 1], json)
// 'found'
-
apply() changes in-place (mutable)
-and before you think 'hey this guy has never seen that Rich Hickey talk' - I have seen that one.
most javascript implementations call .clone() over and over. -
- sneaky-append - an 'add' patch on an array doesn't need an index, and assumes a push on an array:
let json = { foo: [1] }
// according to the spec, this must be '/foo/[index]', which seemed annoying
let patch = { op: 'add', path: '/foo', value: 2 }
json = apply(patch, json) //normally this would be an arror
// {foo: [1, 2]}
- - sneaky-splat - an 'add' patch on an object doesn't need an key, if the value is also an object:
let json = { foo: { bar: true } }
let patch = { op: 'add', path: '/foo', value: { baz: true } }
apply(patch, json) //this would normally be an error, i think.
// { foo: { bar: true, baz: true } }
API
- make(props) - create a JSON pointer from a list of properties
- get(pntr,json) - use a pointer to get data out of JSON
- apply(patch, json) - make modifications to a JSON object (in place)
all the different build formats are in ./builds
there's a get only build, that is < 1kb:
import { get } from 'garbage-patch'
const get = require('garbage-patch/get')
See Also
- json-patch - 7kb
- fast-json-patch - 12kb
- json-8 - 11kb
- jiff - 12kb
MIT