Heim  >  Artikel  >  Backend-Entwicklung  >  Python中字典和JSON互转操作实例

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

WBOY
WBOYOriginal
2016-06-10 15:18:131291Durchsuche

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

其他

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn