# !usr/bin/env python
# -*- coding:UTF-8 -*-
import json
from ruamel import yaml
def json2yaml(in_file):
try:
with open(in_file, 'r', encoding='utf-8') as f:
data = json.load(f)
except FileNotFoundError:
print('无法打开指定文件')
try:
with open('out.yaml', 'w', encoding='utf-8') as fw:
yaml.dump(data, fw, Dumper=yaml.RoundTripDumper, allow_unicode=True)
except:
print('无法写入文件!')
"""
字典是无序的 如何保证写出到yaml是顺序是正确的 ===>> 导入模块:ruamel.yaml
"""
if __name__ == '__main__':
json2yaml('in.json')
另外,使用OrderedDict可以得到一个有序的字典:
from collections import OrderedDict
dd = OrderedDict()
dd[xxx] = 'yyy'
dd[yyy] = 'xxx'
附ruamel模块连接:https://yaml.readthedocs.io/en/latest/install.html