概要

本文介绍如何利用Python解析Json配置文件。

Json文件语法

Json文件是常用的一种配置文件格式。其语法格式简单明了。例如下面是一段Json文件:

config.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"host": {
"name": "Jack",
"age": 22,
"port": 8088,
"skills": ["basketball","cooking","programming"]
},

"visitor": {
"name": "Alice",
"age": 15,
"port": 8089,
"skills": ["dancing","singing"]
}
}

Python解析Json文件

利用json.load()函数可以解析json文件内容,返回一个嵌套的dict对象,其嵌套结构与json结构相同。例如解析上面的json文件:

1
2
3
4
5
6
7
8
9
import json

file = open("config.json")
cfg = json.load(file)
file.close()

print(cfg["host"])
print(cfg["visitor"])
print(cfg["visitor"]["skills"])

得到如下结果:

1
2
3
{'name': 'Jack', 'age': 22, 'port': 8088, 'skills': ['basketball', 'cooking', 'programming']}
{'name': 'Alice', 'age': 15, 'port': 8089, 'skills': ['dancing', 'singing']}
['dancing', 'singing']

Python生成Json文件

利用json.dumps()可以将python数据结构转化为json字符串,直接用write()函数写入json文件即可:(注意添加indent参数,设置换行缩进位数,否则会写到一行里,不易读)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import json

# read json file:
file = open("config.json")
cfg = json.load(file)
file.close()
print(cfg["host"])
print(cfg["visitor"])
print(cfg["visitor"]["skills"])

# write json file:
file2 = open("config2.json","w")
cfg["visitor"]["hobbies"] = ["reading","hiking"]
str = json.dumps(cfg,indent=2)
file2.write(str)
file2.close()

生成的config2.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
{
"host": {
"name": "Jack",
"age": 22,
"port": 8088,
"skills": [
"basketball",
"cooking",
"programming"
]
},
"visitor": {
"name": "Alice",
"age": 15,
"port": 8089,
"skills": [
"dancing",
"singing"
],
"hobbies": [
"reading",
"hiking"
]
}
}

参考