Last active
October 14, 2015 23:54
-
-
Save brent-hoover/8bf8b4dfed2c5d2c8805 to your computer and use it in GitHub Desktop.
Escape all values in a recursive dictionary. Great for sanitizing JSON inputs
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
def escape(s): | |
escaped = unicode(s)\ | |
.replace('&', '&')\ | |
.replace('<', '>')\ | |
.replace('>', '<')\ | |
.replace("'", ''')\ | |
.replace('"', '"') | |
return escaped | |
def escape_dict(data): | |
""" | |
Recursively escape all values in a dictionary | |
:param data: | |
:return: escaped dictionary | |
:rtype: dict | |
""" | |
if isinstance(data, list): | |
for x, l in enumerate(data): | |
if isinstance(l, dict) or isinstance(l, list): | |
escape_dict(l) | |
else: | |
if l is not None: | |
data[x] = escape(l) | |
if isinstance(data, dict): | |
for k, v in data.iteritems(): | |
if isinstance(v, dict) or isinstance(v, list): | |
escape_dict(v) | |
else: | |
if v is not None: | |
data[k] = escape(v) | |
return data | |
if __name__ == '__main__': | |
data = {'name': 'brent', | |
'address': { | |
'line1': '<strong>8008 Norton Ave #2</strong>', | |
'city': '&West Hollywood', | |
'state': 'CA', | |
'other_name': | |
{'nick"Nick"_name': 'Freddy', 'pet_name': 'honey bunch'}, | |
'silly_names': | |
["jimmy 'this jimmy' jones", '<strong>perplexed</strong>', 'sandwich'] | |
}} | |
escaped_data = escape_dict(data) | |
print(escaped_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment