21 January 2016
More as an example than anything else, I wanted a function that would take two JSONB objects in PostgreSQL, and return how the left-hand side differs from the right-hand side. This means any key that is in the left but not in the right would be returned, along with any key whose value on the left is different from the right.
Here’s a quick example of how to do this in a single SELECT. In real life, you probably want more error checking, but it shows how nice the built-in primitives are:
CREATE OR REPLACE FUNCTION json_diff(l JSONB, r JSONB) RETURNS JSONB AS $json_diff$ SELECT jsonb_object_agg(a.key, a.value) FROM ( SELECT key, value FROM jsonb_each(l) ) a LEFT OUTER JOIN ( SELECT key, value FROM jsonb_each(r) ) b ON a.key = b.key WHERE a.value != b.value OR b.key IS NULL; $json_diff$ LANGUAGE sql;