| 范文 | JSON是一种轻量级的数据交换格式,各种语言都有良好的支持。字典是Python的一种数据结构。可以看成关联数组。
 有些时候我们需要设计到字典转换成JSON序列化到文件,或者从文件中读取JSON。简单备忘一下。
 Dict转JSON写入文件
 代码如下:
 #!/usr/bin/env python
 # coding=utf-8
 import json
 d = {'first': 'One', 'second':2}
 json.dump(d, open('/tmp/result.txt', 'w'))
 写入结果
 代码如下:
 cat /tmp/result.txt
 {"second": 2, "first": "One"}
 读取JSON
 代码如下:
 #!/usr/bin/env python
 # coding=utf-8
 import json
 d = json.load(open('/tmp/result.txt','r'))
 print d, type(d)
 运行结果
 代码如下:
 {u'second': 2, u'first': u'One'} <type 'dict'>
 其他
 |