Skip to content

Instantly share code, notes, and snippets.

@mitallast
Created October 26, 2015 10:45
Show Gist options
  • Save mitallast/6076a96d89a1b533ca21 to your computer and use it in GitHub Desktop.
Save mitallast/6076a96d89a1b533ca21 to your computer and use it in GitHub Desktop.
merge json object at postgresql with plpythonu
CREATE LANGUAGE PLPYTHONU;
CREATE OR REPLACE
FUNCTION merge_json(left JSON, right JSON)
RETURNS JSON AS $$
import simplejson as json
def merge(source, destination):
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
else:
destination[key] = value
return destination
l, r = json.loads(left), json.loads(right)
l = merge(l, r)
j = json.dumps(l)
return j
$$ LANGUAGE PLPYTHONU;
UPDATE my_table SET my_field = merge_json(my_field::json, '{"foo":{"bar":true}}'::json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment