merging JSON objects with jpt 1.0

A cool new feature for jpt 1.0 is the ability perform additional merging operations beyond JSON Merge Patch (RFC 7396). To start with let’s check out a JSON Merge Patch operation, using the mergepatch operation:

#key "a" is overwritten with the -v value, "b" is removed because null
% jpt -i0 -o mergepatch -v '{"a":"🟒","b":null}' <<< '{"a":"πŸ”΄","b":"🟑"}'                                                                           
{"a":"🟒"}

# use -u to encode all characters above 0x7E with \u escaping
% jpt -u -i0 -o mergepatch -v '{"a":"🟒","b":null}' <<< '{"a":"πŸ”΄","b":"🟑"}'                                                                           
{"a":"\ud83d\udfe2"}

Only one key survives, since the Merge Patch spec says that any key with a null value will delete that key in the input JSON. Now perhaps you might want null to survive, if so, use the merge operation:

jpt -i0 -o merge -v '{"a":"🟒","b":null}' <<< '{"a":"πŸ”΄","b":"🟑"}' 
{"a":"🟒","b":null}

Now for the more advanced modes. -o merge0 will only merge in keys that do not exist. Existing keys remain untouched. To order the keys alphabetically use -O (the letter O)

% jpt -O -o merge0 -v '{"common":"🟒","uniqToMergeData":"🟒"}' <<< '{"common":"πŸ”΄","uniqToSource":"πŸ”΄"}'
{
  "common": "πŸ”΄",
  "uniqToMergeData": "🟒",
  "uniqToSource": "πŸ”΄"
}

As you can see only the uniqToMergeData key comes through, the other two keys common and uniqToSource do not change. Useful if you are upgrading an object to a newer format and want to retain existing key values and only add the new keys with empty or default values.

merge1 let’s us do the inverse of merge0 and merge only the keys that exist in the target JSON. Keys that do not exist do not merge over.

% jpt -o merge1 -v '{"uniqToMergeData":"🟒","common":"🟒"}' <<< '{"uniqToSource":"πŸ”΄","common":"πŸ”΄"}'
{
  "uniqToSource": "πŸ”΄",
  "common": "🟒"
}

If you like pictures (I sure do) and are a visual learner you can think of merge0 and merge1 like the Exclude and Intersect Shape Areas in Photoshop.

I hope these new merge modes could be useful to you, if you have a Mac (or *nix with jsc installed) download jpt from my GitHub Releases page and give it a go!