5👍
✅
If you want json.dumps
to maintain the special characters I think you may find useful the arguments ensure_ascii=False
.
- Take a look at this answer: Unicode values in strings are escaped when dumping to JSON in Python
- This is the docs for
json.dumps
Instead of doing it yourself, ensure_ascii=False
I think will solve the problem of json
escaping the output.
Ex:
json.dumps({'h':u'\xc2\xa3'},ensure_ascii=False)
>>>u'{"h": "\xc2\xa3"}'
UPDATE: Comparison of json.dumps
with and without ensure_ascii
and a unicode string:
In [7]: json.dumps({'a':u'\u00a3'},ensure_ascii=False)
Out[7]: u'{"a": "\xa3"}'
In [8]: json.dumps({'a':u'\u00a3'})
Out[8]: '{"a": "\\u00a3"}'
Hope this helps!
0👍
I can’t reproduce this. I tried both giving json.dumps Unicode objects and UTF-8 encoded byte strings, and in both cases I got the correctly Unicode escaped json data out:
>>> json.dumps({'foo': u'lölölö'})
'{"foo": "l\\u00f6l\\u00f6l\\u00f6"}'
>>> json.dumps({'foo': u'lölölö'.encode('utf8')})
'{"foo": "l\\u00f6l\\u00f6l\\u00f6"}'
I tried this in Python 2.6 and 2.7, as well as in Python 3.1:
>>> json.dumps({'foo': 'lölölö'})
'{"foo": "l\\u00f6l\\u00f6l\\u00f6"}'
- [Django]-Django management command without working db connection
- [Django]-Jenkins not failing on tests that fail in coverage
- [Django]-Deploying django to AWS Lambda connecting to RDS MySQL, showing error: NameError: name '_mysql' is not defined
- [Django]-How does one create a custom 403 page in Django?
Source:stackexchange.com