Python Shell处理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
27
28
29
30
31
32
33
34
{
"status": "success",
"timestamp": "2025-07-21T10:00:00Z",
"data": [
{
"host": "server-01",
"metrics": {
"cpu": {
"usage": 35.6,
"cores": 4
},
"memory": {
"total": 32768,
"used": 16384,
"unit": "MB"
},
"disk": [
{
"mount": "/",
"total": 512000,
"used": 400000,
"unit": "MB"
}
],
"network": {
"eth0": {
"rx_bytes": 123456789,
"tx_bytes": 987654321
}
}
}
}
]
}

shell

1
2
cat /tmp/data.json | jq '.data[0].metrics.memory.total'
# 32768
1
2
cat /tmp/data.json | jq -r '.data[] | "\(.host): total memory = \(.metrics.memory.total) MB"'
# server-01: total memory = 32768 MB

Python

1
2
3
4
5
6
7
8
9
10
import json

# 读取 JSON 文件
with open('/tmp/data.json', 'r') as f:
data = json.load(f)

# 获取 memory total 的值
total_memory = data['data'][0]['metrics']['memory']['total']
print(total_memory)
# 32768

遍历所有主机

1
2
3
4
5
for host_data in data['data']:
host = host_data.get('host')
total_mem = host_data['metrics']['memory']['total']
print(f"{host}: total memory = {total_mem} MB")
# server-01: total memory = 32768 MB