0%

python convert yaml to json

Guide

1
2
3
4
5
6
7
8
9
10
11
mylinks:

- nickname: 官方博客
avatar: https://kezunlin.me/images/kezunlin_avatar.jpg
site: https://kezunlin.me
info: C++ && Python. CV && DL.

- nickname: 闪烁之狐
avatar: https://blinkfox.github.io/medias/logo.png
site: https://blinkfox.github.io/
info: blinkfox

output.json

1
2
3
4
5
6
7
8
9
10
11
12
13
[{
"avatar": "https://kezunlin.me/images/kezunlin_avatar.jpg",
"name": "官方博客",
"introduction": "C++ && Python. CV && DL.",
"url": "https://kezunlin.me",
"title": "前去学习"
}, {
"avatar": "https://blinkfox.github.io/medias/logo.png",
"name": "闪烁之狐",
"introduction": "blinkfox",
"url": "https://blinkfox.github.io/",
"title": "前去学习"
}]

code

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
import yaml 
import json

result_list = []
with open('./links.yaml') as f:
obj = yaml.load(f) # dict
#print(obj["mylinks"])

for item in obj["mylinks"]:
if 0:
print(item["nickname"])
print(item["avatar"])
print(item["site"])
print(item["info"])
new_item = {
"avatar": item["avatar"],
"name": item["nickname"],
"introduction": item["info"],
"url": item["site"],
"title": "前去学习"
}
result_list.append(new_item)

str_pretty_result = json.dumps(
result_list, indent=4,
sort_keys=True, ensure_ascii=False)

with open("friends.json","w") as f:
f.write(str_pretty_result)

Reference

History

  • 2019/11/29: created.