网络编程
位置:首页>> 网络编程>> Python编程>> Python中字典和JSON互转操作实例

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

作者:junjie  发布时间:2023-03-12 14:18:11 

标签:Python,字典,JSON

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

其他

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com