json
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
json是我们在制作爬虫时非常常见的网络对象,本文就列举python对于json的基本操作。
json函数
使用json函数首先要导入 json 库 即 import json
主要使用以下两个函数:
- json.dumps 将 Python 对象编码成 JSON 字符串
- json.loads 将已编码的 JSON 字符串解码为 Python 对象
json.dumps
json.dumps 用于将 Python 对象编码成 JSON 字符串。
语法:
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding=
"
utf-8
"
,
default=None, sort_keys=False, **kw)
实例:
import
json
data
= [{
'
A
'
:1,
'
B
'
:2,
'
C
'
:3
}]
datajson
=
json.dumps(data)
print
(datajson)
输出:
[{
"
A
"
: 1,
"
B
"
: 2,
"
C
"
: 3}]
常用参数详解
1)skipkeys参数,在编码成json过程中,dict对象的key只可以是string对象,如果是其他类型,那么在编码过程中就会抛出ValueError的异常。skipkeys可以跳过那些非string对象的处理,只处理正确的编码。
2)输出真正的中文需要指定ensure_ascii=False,默认配置使用的ascii编码,所以默认只会输出ASCII字符。
3)indent参数根据数据格式缩进显示,读起来更加清晰, indent的值,代表缩进空格式
import
json
data
= [{
'
A
'
:1,
'
B
'
:2,
'
C
'
:3
}]
datajson
=
json.dumps(data)
print
(datajson)
datajson2
=json.dumps(data,indent=4
)
print
(datajson2)
输出:
[{
"
A
"
: 1,
"
B
"
: 2,
"
C
"
: 3
}]
[
{
"
A
"
: 1
,
"
B
"
: 2
,
"
C
"
: 3
}
]
4)separators参数的作用是去掉‘,’ ‘:’后面的空格,在传输数据的过程中,越精简越好,冗余的东西全部去掉。
import
json
data
= [{
'
A
'
:1,
'
B
'
:2,
'
C
'
:3
}]
datajson
=
json.dumps(data)
print
(datajson)
datajson2
=json.dumps(data,separators=(
'
,
'
,
'
:
'
))
print
(datajson2)
输出:
[{
"
A
"
: 1,
"
B
"
: 2,
"
C
"
: 3
}]
[{
"
A
"
:1,
"
B
"
:2,
"
C
"
:3}]
5)sort_keys是告诉编码器按照字典key排序(a到z)输出。
import
json
data
= [{
'
A
'
:1,
'
D
'
:2,
'
C
'
:3
}]
datajson
=
json.dumps(data)
print
(datajson)
datajson2
=json.dumps(data,sort_keys=
True)
print
(datajson2)
输出:
[{
"
A
"
: 1,
"
D
"
: 2,
"
C
"
: 3
}]
[{
"
A
"
: 1,
"
C
"
: 3,
"
D
"
: 2}]
python 原始类型向 json 类型的转化对照表:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str, unicode | string |
| int, long, float | number |
| True | true |
| False | false |
| None | null |
json.loads
json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
import
json
jsonData
=
'
{"a":1,"b":2,"c":3,"d":4,"e":5}
'
print
(json.loads(jsonData))
输出:
{
'
a
'
: 1,
'
b
'
: 2,
'
c
'
: 3,
'
d
'
: 4,
'
e
'
: 5}
以下代码表示存储json文件以及读取json文件
import
json
data
= [{
'
A
'
:1,
'
D
'
:2,
'
C
'
:3},{
'
a
'
:1,
'
b
'
:2,
'
c
'
:3
}]
with open(
'
test.json
'
,
'
w
'
) as jsfile:
jsfile.write(json.dumps(data))
with open(
'
test.json
'
,
'
r
'
) as jsfile:
print
(json.loads(jsfile.read()))
json 类型转换到 python 的类型对照表:
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | unicode |
| number (int) | int, long |
| number (real) | float |
| true | True |
| false | False |
| null | None |

