Skip to content

Instantly share code, notes, and snippets.

@menski
Created February 28, 2019 16:00
Show Gist options
  • Save menski/ace04626c6ab0c14cb28c79a01a14d3d to your computer and use it in GitHub Desktop.
Save menski/ace04626c6ab0c14cb28c79a01a14d3d to your computer and use it in GitHub Desktop.
Anonymise JSON
import json
import random
import string
def random_string(length):
return ''.join([random.choice(string.ascii_letters) for n in range(length)])
def random_bool():
return random.choice([True, False])
def random_int(end):
return random.randrange(0, 1000 + end)
def randomize(value):
if isinstance(value, str):
return random_string(len(value))
elif isinstance(value, int):
return random_int(value)
elif isinstance(value, bool):
return random_bool()
elif isinstance(value, list):
return [randomize(v) for v in value]
elif isinstance(value, dict):
return {random_string(len(k)):randomize(v) for (k, v) in value.items()}
elif value == None:
return value
else:
print("Unsupported type", key, type(value))
with open('payload.json', 'r') as f:
payload = json.load(f)
anon = dict()
for key in payload:
newKey = random_string(len(key))
anon[newKey] = randomize(payload[key])
with open('anon.json', 'w') as f:
json.dump(anon, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment