【发布时间】:2019-01-25 14:59:43
【问题描述】:
我是 python 新手,所以我正在构建一个简单的程序来将 YAML 解析为 JSON 并将 JSON 解析为 YAML。
yaml2json 在一行中将 YAML 转换为 JSON,但 JSON 验证器说它是正确的。
这是我目前的代码:
def parseyaml(inFileType, outFileType):
infile = input('Please enter a {} filename to parse: '.format(inFileType))
outfile = input('Please enter a {} filename to output: '.format(outFileType))
with open(infile, 'r') as stream:
try:
datamap = yaml.safe_load(stream)
with open(outfile, 'w') as output:
json.dump(datamap, output)
except yaml.YAMLError as exc:
print(exc)
print('Your file has been parsed.\n\n')
def parsejson(inFileType, outFileType):
infile = input('Please enter a {} filename to parse: '.format(inFileType))
outfile = input('Please enter a {} filename to output: '.format(outFileType))
with open(infile, 'r') as stream:
try:
datamap = json.load(stream)
with open(outfile, 'w') as output:
yaml.dump(datamap, output)
except yaml.YAMLError as exc:
print(exc)
print('Your file has been parsed.\n\n')
原始 YAML 与新 YAML 的示例
原文:
inputs:
webTierCpu:
type: integer
minimum: 2
default: 2
maximum: 5
title: Web Server CPU Count
description: The number of CPUs for the Web nodes
新:
inputs:
dbTierCpu: {default: 2, description: The number of CPUs for the DB node, maximum: 5,
minimum: 2, title: DB Server CPU Count, type: integer}
它看起来不像是解码所有 JSON,所以我不确定下一步应该去哪里......
【问题讨论】:
-
解析后的输出看起来包含所有相同的数据(除了标题和描述中的不同文本,只是包含在大括号内且顺序不同。
-
YAML 是 JSON 的超集。或者换句话说:有效的 JSON 也是有效的 YAML。 (不是相反)
-
您无法重新复制原始 YAML,因为在转换为 JSON 时会丢失换行符和顺序。
-
在您的
parseyaml中,except之前存在缩进错误。 -
@Daniel 我不确定您所说的“换行符 [...] 迷路”是什么意思,但无论如何您的结论似乎都是无效的。中间 JSON 流当然有一个明确的顺序,就像 YAML 源一样,并且在保留该顺序的同时将具有明确顺序的 Mapping 转储到 JSON 是相对简单的。加载 JSON 保留顺序更加简单。