Home  >  Article  >  Backend Development  >  Python中字典和JSON互转操作实例

Python中字典和JSON互转操作实例

WBOY
WBOYOriginal
2016-06-10 15:18:131294browse

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

其他

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn