simple json dumps function with unicode

2019-05-19 17:23发布

问题:

Here is a sample run of simple json using python2.4 version

>>> 
>>> orig='{"key1":"Val", "key2":"val2"}'
>>> origDict = simplejson.loads(orig)
>>> origDict
{'key2': 'val2', 'key1': 'Val'}
>>> origDict['key2'] = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> simplejson.dumps(origDict)
'{"key2": "\\u4f60\\u597d", "key1": "Val"}'

The dumps functions is replacing the byte string with the unicode version. Is there a way to make it not do that and just return '{"key2": "\xe4\xbd\xa0\xe5\xa5\xbd", "key1": "Val"}' ?

回答1:

Pass ensure_ascii=False and encode manually after.