python convert yaml to json


Guide

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

[{
    "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

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.

Author: kezunlin
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source kezunlin !
评论
  TOC