Akemi

Python json模块案例—提取与交换json数据

2024/11/09

json格式大体是一个字典的格式,而众所周知字典是什么类型的数据都可以嵌套进去的

方法介绍:

1.json.dump()
将python对象转换为json格式写入文件

json.dumps()
将python对象转换为json格式输出

2.json.load
文件中读取json数据,转换为python对象

json.loads
将json数据转换为python对象

读取与重新写入配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"service_name": "MyApp",
"version": "1.0.0",
"logging": {
"level": "INFO",
"log_file": "app.log",
"log_format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"database": {
"host": "localhost",
"port": 5432,
"user": "db_user",
"password": "secure_password",
"database_name": "my_database"
},
"server": {
"host": "0.0.0.0",
"port": 8080,
"timeout": 30,
"max_connections": 100
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#coding=utf-8
import json

with open('config','r') as file:
# 读取并写入config
config=json.load(file)

# 修改config这个字典
config['version']='1.0.1'

with open('config','w') as file:
# 将config重新写入文件,indent表示换行 缩进
json.dump(config,file,indent=2)

收集硬件状态并写入json文件

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
#coding=utf-8
import json
import psutil
import shutil
from datetime import datetime
from time import sleep

status_data=[]

# 定时收集服务器状态

for i in range(5):
status={
'timestamp': datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
'cpu_usage': psutil.cpu_percent(),
'memory_usage': psutil.virtual_memory().percent,
'disk_total': f"{shutil.disk_usage('/').total/(2**30):.2f}GiB",
'disk_usage': f"{shutil.disk_usage('/').used/(2**30):.2f}GiB",
'disk_free': f"{shutil.disk_usage('/').free/(2**30):.2f}GiB"
}
# 将字典追加到列表中
status_data.append(status)
sleep(1)

with open('server_status.json','w',encoding='utf-8') as file:
json.dump(status_data,file,indent=2)

修改权限文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"user123": {
"username": "user123",
"access_level": "user",
"last_login": "2028-09-28 18:18:45",
"active": true
},
"user456": {
"username": "user456",
"access_level": "admin",
"last_login": "2028-09-18 10:18:30",
"active": true
},
"user789": {
"username": "user789",
"access_level": "guest",
"last_login": "2028-09-08 09:18:05",
"active": false
}
}
1
2
3
4
5
6
7
8
9
#coding=utf-8
import json
with open('permiss.json','r') as f:
# 转成字典,赋给permission
permission=json.load(f)
# 修改字典的内容
permission['user123']['access_level']='admin'
with open('permiss.json','w') as f:
json.dump(permission,f,indent=4)
CATALOG