Skip to content

Instantly share code, notes, and snippets.

@ptmcg
Last active March 9, 2020 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptmcg/62231fb585d3a6b2b24fc3ea0576077c to your computer and use it in GitHub Desktop.
Save ptmcg/62231fb585d3a6b2b24fc3ea0576077c to your computer and use it in GitHub Desktop.
Simple JSON item accessor
#
# simple JSON item accessor
#
import json
def json_accessor(fn):
def _inner(src, keypath, *args):
if not isinstance(keypath, (tuple, list)):
keypath = [keypath]
src_dict = json.loads(src)
cur_item = src_dict
for key in keypath:
cur_item = cur_item[key]
fn(cur_item, *args)
return json.dumps(src_dict)
return _inner
@json_accessor
def append(item, value):
item.append(value)
@json_accessor
def replace(item, index, value):
item[index] = value
@json_accessor
def replace_value(item:list, cur_value, new_value):
index = item.index(cur_value)
item[index] = new_value
@json_accessor
def remove_at(item, index):
del item[index]
@json_accessor
def remove_value(item, value):
item.remove(value)
if __name__ == '__main__':
# requires Python 3.8 for f-strings with '='
src = """{"myarray": [1,2,3]}"""
print(f"{src=}")
print(f"{append(src, 'myarray', 5)=}")
print(f"{replace(src, 'myarray', 2, 5)=}")
print(f"{replace_value(src, 'myarray', 2, 12)=}")
print(f"{remove_at(src, 'myarray', 0)=}")
print(f"{remove_value(src, 'myarray', 2)=}")
src = """{"root": {"myarray": [1,2,3]}}"""
print(f"{src=}")
print(f"{append(src, ['root', 'myarray'], 5)=}")
print(f"{replace(src, ['root', 'myarray'], 2, 5)=}")
print(f"{replace_value(src, ['root', 'myarray'], 2, 12)=}")
print(f"{remove_at(src, ['root', 'myarray'], 0)=}")
print(f"{remove_value(src, ['root', 'myarray'], 2)=}")
src = """[{"other": [4,5,6]}, {"myarray": [1,2,3]}]"""
print(f"{src=}")
print(f"{append(src, [1, 'myarray'], 5)=}")
print(f"{replace(src, [1, 'myarray'], 2, 5)=}")
print(f"{replace_value(src, [1, 'myarray'], 2, 12)=}")
print(f"{remove_at(src, [1, 'myarray'], 0)=}")
print(f"{remove_value(src, [1, 'myarray'], 2)=}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment