Message info
 
To: From:Django Subject:Re: [Django] #17419: JSON template tag Date:Thu, 29 Mar 2012 06:18:45 -0000
 

#17419: JSON template tag
-------------------------------------+-------------------------------------
Reporter: lau | Owner: aaugustin
Type: New feature | Status: new
Component: Template system | Version: SVN
Severity: Normal | Resolution:
Keywords: json template tag | Triage Stage: Design
Has patch: 1 | decision needed
Needs tests: 0 | Needs documentation: 0
Easy pickings: 0 | Patch needs improvement: 0
| UI/UX: 0
-------------------------------------+-------------------------------------

Comment (by carbonXT):

It's a bit hacky, but we might be able to use JSONEncoder.iterencode to
escape only the string data in the json object. Proof of concept:


{{{
from django.utils import simplejson
from django.utils.html import escape

def encode_as_escaped_json(obj):
result = ''
for part in simplejson.JSONEncoder().iterencode(obj):
if part[0:3] == ', "':
result += ', "' + escape(part[3:-1]) + '"'
elif part[0] == '"':
result += '"' + escape(part[1:-1]) + '"'
else:
result += part
return result

if __name__ == '__main__':
my_obj = [
{'k1': '</script><script>Attack!</script><script>', 'k2': 42},
'e"eer',
'</script><script>More attack!</script><script>',
]
escaped_json = encode_as_escaped_json(my_obj)
print escaped_json
}}}

Running this yields:

{{{
1558]$ python ./tmp.py
[{"k2": 42, "k1":
"</script><script>Attack!</script><script>"},
"e\"eer", "</script><script>More
attack!</script><script>"]
}}}

This works because iterencode() returns string-based dictionary keys and
values as '''"<string>"''', and strings in lists as ''', "<string>"''' .

--
Ticket URL: <https://code.djangoproject.com/ticket/17419#comment:15>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

--
You received this message because you are subscribed to the Google Groups "Django updates" group.
To post to this group, send email to django-updates@googlegroups.com.
To unsubscribe from this group, send email to django-updates+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-updates?hl=en.