Created
October 26, 2015 10:45
-
-
Save mitallast/6076a96d89a1b533ca21 to your computer and use it in GitHub Desktop.
merge json object at postgresql with plpythonu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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