Skip to content

Instantly share code, notes, and snippets.

@samtstern
Created August 26, 2014 16:36
Show Gist options
  • Save samtstern/552d747df410edae574b to your computer and use it in GitHub Desktop.
Save samtstern/552d747df410edae574b to your computer and use it in GitHub Desktop.
Python JSON Tool for doog
import json
import sys
def main():
num_args = len(sys.argv)
if num_args < 4:
print 'Invalid arguments, should be <file> <key> <value>'
else:
file_name = sys.argv[1]
key = sys.argv[2]
val = sys.argv[3]
# Load JSON File
with open(file_name, "r") as json_file:
json_data = json.load(json_file)
# Replace key with value
json_replace(json_data, key, val)
# Write it back
with open(file_name, "w") as write_file:
json_str = json.dumps(json_data, sort_keys=True, indent=2)
write_file.write(json_str)
print 'Done.'
def json_replace(data, key, val):
# Key may reference nested objects with period syntax
key_split = key.split('.')
# Get to deepest level
to_change = data
for nested_key in key_split[:-1]:
to_change = to_change[nested_key]
# Change the value
last_key = key_split[-1]
to_change[last_key] = val
# Run Main
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment