2018年2月7日 星期三

[ Python 常見問題 ] Convert Python dictionary to JSON array

Source From Here 
Question 
Currently I have this dictionary, printed using pprint: 
>>> import json 
>>> from pprint import pprint 
>>> dict = {'name':'john', 'age': 36, 'address': 'New Taipei...', 'LeafTemps': '\xff\xff\xff\xff'} 
>>> pprint(dict) 
{'LeafTemps': '\xff\xff\xff\xff', 
'address': 'New Taipei...', 
'age': 36, 
'name': 'john'}
 
>>> json.dumps(dict) 
Traceback (most recent call last): 
File "", line 1, in  
File "/usr/lib64/python2.7/json/__init__.py", line 243, in dumps 
return _default_encoder.encode(obj) 
File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode 
chunks = self.iterencode(o, _one_shot=True) 
File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode 
return _iterencode(o, 0) 
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

How-To 
If you are fine with non-printable symbols in your json, then add ensure_ascii=False to dumps call. 
>>> json.dumps(dict, ensure_ascii=False) 
'{"age": 36, "LeafTemps": "\xff\xff\xff\xff", "name": "john", "address": "New Taipei..."}'

If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.


沒有留言:

張貼留言

[ Py DS ] Ch1 - IPython: Beyond Normal Python

Source From  Here   Keyboard Shortcuts in the IPython Shell   If you spend any amount of time on the computer, you’ve probably found a u...