Skip to content

Instantly share code, notes, and snippets.

@slhck
Created October 7, 2022 12:25
Show Gist options
  • Save slhck/c0a7401d055eb332026713c34d927948 to your computer and use it in GitHub Desktop.
Save slhck/c0a7401d055eb332026713c34d927948 to your computer and use it in GitHub Desktop.
Decode a nested JSON file containing escaped JSON values
#!/usr/bin/env python3
#
# Decode a nested JSON object containing escaped JSON strings as values
# Pass the JSON file as a command line argument, or use "-" to read from stdin.
import json
def decode_json_object(json_object):
"""Decode a JSON object containing escaped JSON strings as values"""
for key, value in json_object.items():
if isinstance(value, str):
try:
json_object[key] = json.loads(value)
except ValueError:
pass
return json_object
def decode_json(json_string):
"""Decode a nested JSON object containing escaped JSON strings as values"""
return json.loads(json_string, object_hook=decode_json_object)
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <json_file>", file=sys.stderr)
sys.exit(1)
if sys.argv[1] == "-":
json_string = sys.stdin.read()
else:
with open(sys.argv[1]) as f:
json_string = f.read()
print(json.dumps(decode_json(json_string), indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment