Created
September 27, 2016 04:43
-
-
Save InfoSec812/e3ed6544e91349f00e5ada88ccae90a3 to your computer and use it in GitHub Desktop.
PostgreSQL json_patch(TEXT, TEXT) function using PLPYTHON
This file contains hidden or 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
| DROP FUNCTION json_patch(_data TEXT, _patch TEXT) | |
| /* | |
| * On the PostgreSQL host, you will need to install: | |
| * postgresql95-plpython (RedHat/CentOS) | |
| * postgresql-plpython-9.5 (Ubuntu/Debian) | |
| * You will also need to install the jsonpatch library using either easy_install or pip | |
| * pip install jsonpatch | |
| * easy_install jsonpatch | |
| */ | |
| CREATE EXTENSION plpythonu; | |
| CREATE OR REPLACE FUNCTION json_patch(_data TEXT, _patch TEXT) | |
| RETURNS jsonb | |
| LANGUAGE plpythonu AS | |
| $$ | |
| import jsonpatch | |
| import json | |
| patch = jsonpatch.JsonPatch(json.loads(_patch)) | |
| return json.dumps(patch.apply(json.loads(_data))) | |
| $$; | |
| SELECT json_patch('{"boo": "baz"}'::TEXT, '[{"op": "add", "path": "/foo", "value": "bar"},{"op": "add", "path": "/baz", "value": [1, 2, 3]},{"op": "remove", "path": "/baz/1"},{"op": "test", "path": "/baz", "value": [1, 3]},{"op": "replace", "path": "/baz/0", "value": 42},{"op": "remove", "path": "/baz/1"}]') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment