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.


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...