json的使用

json字符串生成json对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
python复制代码import json

str = '''
[{
"name": "Bob",
"gender": "male",
"birthday": "1992-10-18"
}, {
"name": "Selina",
"gender": "female",
"birthday": "1995-10-18"
}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))

json双引号,不能使用单引号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
python复制代码import json

str = '''
[{
'name': 'Bob',
'gender': 'male',
'birthday': '1992-10-18'
}]
'''
data = json.loads(str)

"""
json字符串的key-value都需要使用双引号,不能使用单引号,否则在loads的时候会报错
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5 (char 8)
"""

文件读取json内容

1
2
3
4
5
6
python复制代码import json

with open('data.json', 'r') as file:
str = file.read()
data = json.loads(str)
print(data)

json写入文件

  • json.dumps()会自动将json串中的单引号变成双引号
1
2
3
4
5
6
7
8
9
python复制代码import json

data = [{
'name': 'Bob',
'gender': 'male',
'birthday': '1992-10-18'
}]
with open('data.json', 'w') as file:
file.write(json.dumps(data))

json写入文件,indent指定缩进

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
python复制代码import json

data = [{
'name': 'Bob',
'gender': 'male',
'birthday': '1992-10-18'
}]
with open('data.json', 'w') as file:
file.write(json.dumps(data, indent=2))

"""
文件中的文本格式
[
{
"name": "Bob",
"gender": "male",
"birthday": "1992-10-18"
}
]
"""

中文解码问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
python复制代码import json

data = [{
'name': '李宁',
'gender': '男',
'birthday': '1992-10-18'
}]

with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data, indent=2, ensure_ascii=False))

"""
存在中文
with open('data.json', 'w') as file:
file.write(json.dumps(data, indent=2))
[
{
"name": "\u738b\u4f1f",
"gender": "\u7537",
"birthday": "1992-10-18"
}
]

解决方式:
with open('data.json', 'w', encoding='utf-8') as file:
file.write(json.dumps(data, indent=2, ensure_ascii=False))
"""

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%