Last active
March 7, 2023 04:58
-
-
Save wonderbeyond/22cae14aa553fb137509df2f54b4f728 to your computer and use it in GitHub Desktop.
[python][jsonpath-ng] Use JSONPath to update a specific location of a JSON document.
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
from jsonpath_ng import jsonpath, parse | |
def mod_func(orig, data, field): | |
data[field] *= 2 | |
data = { | |
"foo": [ | |
{"baz": 1}, | |
{"baz": 2}, | |
], | |
"user": { | |
"name": "what" | |
} | |
} | |
expr = parse("user.name") | |
expr.update(data, "Wonder") | |
assert data == {'foo': [{'baz': 1}, {'baz': 2}], 'user': {'name': 'Wonder'}} | |
# Bad case below! we can only update if the specified path exists. | |
expr = parse("user.age") | |
expr.update(data, 18) # No effect! | |
expr = parse("foo[*].baz") | |
expr.update(data, mod_func) | |
assert data == {'foo': [{'baz': 2}, {'baz': 4}], 'user': {'name': 'Wonder'}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment