先要理解 json 的格式
JSON 文件格式中文和其他 unicode 字符的处理
unicode 不属于 JSON 支持的类型,在 .json 文件里写入的是 unicode 代码,比如盛夏 Dive into history, 2009 edition 写成 json 文件
"title": "\u76db\u590f Dive into history, 2009 edition"
Q: 如何控制这个编码?
注意在 open 文件时可以控制文件编码,但是文件编码不同于 .json 内容的编码,不管 .json 文件是什么编码,内容都是
\u76db\u590f
python json module
Dive Into Python 3. Chapter 13. Serializing Python ObjectsAnother tutorial
JSON 支持的数据和 python 数据对应关系:
| Notes | JSON | Python 3 |
|---|---|---|
| object | dictionary | |
| array | list | |
| string | string | |
| integer | integer | |
| real number | float | |
| * | true | True |
| * | false | False |
| * | null | None |
| * All json values are case-sensitive. | ||
dumps(object): dump to string
dump(object, fp): dump to file
1. json.dump() 也只支持上表右侧的数据
2. json.dump() 也可以 dump tuple,它不区分 list 和 tuple,都 dump 成为 array; 当然 json.load load 成为 list
3. 其他的类型通过编写辅助函数,传递给 json.dump 和 json.load 来处理
def to_json(python_object):
if isinstance(python_object, time.struct_time): ①
return {'__class__': 'time.asctime',
'__value__': time.asctime(python_object)} ②
if isinstance(python_object, bytes):
return {'__class__': 'bytes',
'__value__': list(python_object)}
raise TypeError(repr(python_object) + ' is not JSON serializable')
def from_json(json_object): ①
if '__class__' in json_object: ②
if json_object['__class__'] == 'time.asctime':
return time.strptime(json_object['__value__']) ③
if json_object['__class__'] == 'bytes':
return bytes(json_object['__value__']) ④
return json_object
两个较通用的辅助函数见Another tutorial
当控制 dump 的输出后,可以用 JSON 文件来比较两个object
0 comments:
Post a Comment