python中json模块_Python 中 的 json 模块

本文详细介绍了Python中json模块的主要功能,包括序列化和反序列化。通过示例展示了如何使用dumps和loads函数进行编码和解码操作,以及如何通过设置参数实现紧凑编码和格式化输出。同时,文中还提供了处理大量JSON数据的示例,展示了如何将数据写入和读取到文件中。
摘要由CSDN通过智能技术生成

python 中的json 模板主要的两个功能:序列化和反序列化

序列化: encoding 将python 数据 编码成json 字符串

对应的函数有 dump 和 dumps

反序列化: decoding 将json 字符串 解码成 python 数据

对应的函数有 load 和 loads

json 序列化 dumps 实例:

Base example>>> import json

>>> data=['foo', {'bar': ('baz', None, 1.0, 2)}]

>>> print data

['foo', {'bar': ('baz', None, 1.0, 2)}]

>>> json_data=json.dumps(data)

>>> print json_data

["foo", {"bar": ["baz", null, 1.0, 2]}]

>>>

Compact encoding(压缩编码)>>> import json

>>> data = [1,2,3,{'4': 5, '6': 7}]

>>> print data

[1, 2, 3, {'4': 5, '6': 7}]

>>> data_json = json.dumps(data)

>>> print data_json

[1, 2, 3, {"4": 5, "6": 7}]

>>> data_json2 = json.dumps(data,sort_keys=True)

>>> print data_json2

[1, 2, 3, {"4": 5, "6": 7}]

>>> data_json2 = json.dumps(data,sort_keys=True,separators=(',',':'))

>>> print data_json2

[1,2,3,{"4":5,"6":7}]

参数 separators 将 , 和 : 后门的空格剔除掉了。 separators 的值必须是一个 tuple

帮助中的英文注释:

If specified, separators should be a (item_separator, key_separator) tuple.

The default is (', ', ': '). To get the most compact JSON

representation you should specify (',', ':') to eliminate whitespace.

Pretty printing(一种格式化输出)>>> data_json3 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'))

>>> print data_json3

[

1,

2,

3,

{

"4":5,

"6":7

}

]

indent 会让每个键值对显示的时候,以缩进几个字符对齐。以方便查看

帮助中的英文注释:

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines.None is the most compact representation. Since the default item separator is ', ', the output might include trailing whitespace when indent is specified. You can use separators=(',', ': ') to avoid this.

josn 反序列化 loads 实例:>>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

>>> str_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'

>>> obj2 = json.loads(str_json)

>>> print obj2

[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

>>> obj2 == obj

True

大数据处理:

以上不论时序列化的dumps 和 反序列化的loads 。所针对的数据都是一个json 字符串 或者时 一个python 的数据结构。那么当遇到了大量的json数据(如一个json 的配置文件)

或者 将一个python 的数据结构导出成一个json 的配置文件。#! /usr/bin/env python

# _*_ encoding: utf-8 _*_

import json

# dump example

data = [{'lang':('python','java'),'school':"beijing"},"God"]

f = open('test.json','w+')

json.dump(data,f)

f.flush()

f.close()

# load example

fd = file("test.json")

js = json.load(fd)

print js

奇淫巧计:

python 的 json 结合 shell 输出$ echo '{"json":"obj"}' | python -m json.tool

{

"json": "obj"

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值