Created
December 6, 2016 10:17
-
-
Save phillip-haydon/54871b746201793990a18717af8d70dc to your computer and use it in GitHub Desktop.
Deep Merge two jsonb documents in PostgreSQL
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 OR REPLACE FUNCTION jsonb_merge(left JSONB, right JSONB) RETURNS JSONB AS $$ | |
var mergeJSON = function (target, add) { | |
function isObject(obj) { | |
if (typeof obj == "object") { | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
return true; // search for first object prop | |
} | |
} | |
} | |
return false; | |
} | |
for (var key in add) { | |
if (add.hasOwnProperty(key)) { | |
if (target[key] && isObject(target[key]) && isObject(add[key])) { | |
mergeJSON(target[key], add[key]); | |
} else { | |
target[key] = add[key]; | |
} | |
} | |
} | |
return target; | |
}; | |
return mergeJSON(left, right); | |
$$ LANGUAGE plv8; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@phillip-haydon I didn't come here for merging arrays. That's not what the function in the gist does.
I'm not even sure how you would want to merge arrays other than a simple concatenation.