最新消息:

Python中字典序列化操作

python admin 3478浏览 0评论

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'>

转载请注明:爱开源 » Python中字典序列化操作

您必须 登录 才能发表评论!