import json
import yaml
import sys
from collections import OrderedDict
def json2yaml(json_filename, yaml_filename):
# 读取 JSON 文件
with open(json_filename, 'r') as json_file:
data = json.load(json_file)#, object_pairs_hook=OrderedDict)
# 将数据写入 YAML 文件
with open(yaml_filename, 'w') as yaml_file:
yaml.dump(data, yaml_file, default_flow_style=False)
print(f'JSON file {json_filename} has been converted to YAML file {yaml_filename}.')
def json2tsv(json_filename, tsv_filename):
# 读取 JSON 文件
with open(json_filename, 'r') as json_file:
raw_data = json.load(json_file)#, object_pairs_hook=OrderedDict)
js_key = list(raw_data.keys())[0]
data = list(raw_data.values())[0]
# 将数据写入 TSV 文件
with open(tsv_filename, 'w') as tsv_file:
# json 的大类
tsv_file.write(js_key + '\n')
# 获取 JSON 数据中的键(假设所有对象有相同的键)
title = list(data[0].keys())
# 写入 TSV 文件的标题行(使用制表符分隔)
tsv_file.write('\t'.join(title) + '\n')
# 遍历 JSON 数据并将其转换为 TSV 格式
for item in data:
# print(item)
values = [str(item[key]) for key in title]
tsv_file.write('\t'.join(values) + '\n')
print(f'JSON file {json_filename} has been converted to TSV file {tsv_filename}.')
if __name__ == '__main__':
input_file = sys.argv[1]
output_file = sys.argv[2]
json2tsv(input_file, output_file)
json格式转换 ymal tsv
最新推荐文章于 2024-03-17 09:40:16 发布