Skip to content

Instantly share code, notes, and snippets.

@zenweasel
Last active October 14, 2015 23:54
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 zenweasel/8bf8b4dfed2c5d2c8805 to your computer and use it in GitHub Desktop.
Save zenweasel/8bf8b4dfed2c5d2c8805 to your computer and use it in GitHub Desktop.
Escape all values in a recursive dictionary. Great for sanitizing JSON inputs
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def escape(s):
escaped = unicode(s)\
.replace('&', '&')\
.replace('<', '&gt;')\
.replace('>', '&lt;')\
.replace("'", '&#39;')\
.replace('"', '&#34;')
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