python保存和读取json文件

json是一种数据存储文件,适合存储结构化的数据,json官网

json文件的读取

一般来说,json中的内容是字典格式,如下

1
2
3
4
5
6
7
8
{
"image": "1.png",
"category": "cat",
"info": {
"bbox": [1,2,3,4],
"point": [1.2, 3.2]
}
}

现在我们读取其中的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
import json
import json
f = open('num.json', 'r')
content = f.read()
a = json.loads(content)
print(type(a))
print(a)
f.close()

'''
<class 'dict'>
{'image': '1.png', 'category': 'cat', 'info': {'bbox': [1, 2, 3, 4], 'point': [1.2, 3.2]}}
'''

json数据的保存

下面我们保存json文件

1
2
3
4
5
6
7
8
9
10
11
12
13
import json
a = {
"image": "1.png",
"category": "cat",
"info": {
"bbox": [1,2,3,4],
"point": [1.2, 3.2]
}
}
b = json.dumps(a)
f2 = open('new_json.json', 'w')
f2.write(b)
f2.close()

此时打开new_json.json文件,他的内容如下

1
{"image": "1.png", "category": "cat", "info": {"bbox": [1, 2, 3, 4], "point": [1.2, 3.2]}}

这和我们刚才的展示效果有所差别,因为他们写在了一整行,不利于阅读,想要格式化保存,只需要将dumps函数改为json.dumps(a, indent=4)即可,indent表示缩进的大小,缩进后的数据如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"image": "1.png",
"category": "cat",
"info": {
"bbox": [
1,
2,
3,
4
],
"point": [
1.2,
3.2
]
}
}
Error: API rate limit exceeded for 34.195.68.102. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)