- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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 进行解码,所以我不确定下一步应该去哪里......
最佳答案
您的文件正在丢失其格式,因为原始的 dump
例程默认情况下以 YAML 流式写入所有叶节点,而您的输入是 block 式一路走来。
您还丢失了键的顺序,首先是因为 JSON 解析器使用 dict,其次是因为 dump
对输出进行排序。
如果您查看中间 JSON,您已经看到键顺序是在那一点上消失了。要保留它,请使用新的 API 加载您的 YAML并有一个特殊的 JSON 编码器作为转储的替代品,可以处理加载 YAML 的 Mapping
的子类,类似于 this例子来自标准 Python 文档。
假设您的 YAML 存储在 input.yaml
中:
import sys
import json
from collections.abc import Mapping, Sequence
from collections import OrderedDict
import ruamel.yaml
# if you instantiate a YAML instance as yaml, you have to explicitly import the error
from ruamel.yaml.error import YAMLError
yaml = ruamel.yaml.YAML() # this uses the new API
# if you have standard indentation, no need to use the following
yaml.indent(sequence=4, offset=2)
input_file = 'input.yaml'
intermediate_file = 'intermediate.json'
output_file = 'output.yaml'
class OrderlyJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Mapping):
return OrderedDict(o)
elif isinstance(o, Sequence):
return list(o)
return json.JSONEncoder.default(self, o)
def yaml_2_json(in_file, out_file):
with open(in_file, 'r') as stream:
try:
datamap = yaml.load(stream)
with open(out_file, 'w') as output:
output.write(OrderlyJSONEncoder(indent=2).encode(datamap))
except YAMLError as exc:
print(exc)
return False
return True
yaml_2_json(input_file, intermediate_file)
with open(intermediate_file) as fp:
sys.stdout.write(fp.read())
给出:
{
"inputs": {
"webTierCpu": {
"type": "integer",
"minimum": 2,
"default": 2,
"maximum": 5,
"title": "Web Server CPU Count",
"description": "The number of CPUs for the Web nodes"
}
}
}
您看到您的 JSON 具有适当的键顺序,我们也需要在加载时保存。你可以在没有子类化的情况下做到这一点任何东西,通过指定将 JSON 对象加载到的子类中映射
,YAML 解析器通过提供object_pairs_hook
在内部使用。
from ruamel.yaml.comments import CommentedMap
def json_2_yaml(in_file, out_file):
with open(in_file, 'r') as stream:
try:
datamap = json.load(stream, object_pairs_hook=CommentedMap)
# if you need to "restore" literal style scalars, etc.
# walk_tree(datamap)
with open(out_file, 'w') as output:
yaml.dump(datamap, output)
except yaml.YAMLError as exc:
print(exc)
return False
return True
json_2_yaml(intermediate_file, output_file)
with open(output_file) as fp:
sys.stdout.write(fp.read())
哪些输出:
inputs:
webTierCpu:
type: integer
minimum: 2
default: 2
maximum: 5
title: Web Server CPU Count
description: The number of CPUs for the Web nodes
而且我希望这与您的原始输入足够相似以便可以接受。
注意事项:
在使用新 API 时,我倾向于使用 yaml
作为 API 的名称ruamel.yaml.YAML()
的实例,而不是 from ruamel import
。然而,这掩盖了
yamlyaml.YAMLError
的使用,因为错误类不是 YAML()
如果您正在开发此类内容,我建议您删除至少来自实际功能的用户输入。它应该是编写 parseyaml
和 parsejson
来调用 yaml_2_json
很简单。json_2_yaml
。
原始 YAML 文件中的任何注释都将丢失,尽管ruamel.yaml 可以加载它们。 JSON 最初确实允许注释,但现在不在规范中,而且我知道没有任何解析器可以输出注释。
由于您的真实文件具有文字 block 标量,您必须使用一些魔法来取回它们。
包括以下遍历树的函数,递归到 dict 值和列表元素中,并将带有嵌入式换行符的任何行转换为一种类型,该类型将输出到 YAML 作为就地文字 block 样式标量(因此没有返回值):
from ruamel.yaml.scalarstring import PreservedScalarString, SingleQuotedScalarString
from ruamel.yaml.compat import string_types, MutableMapping, MutableSequence
def preserve_literal(s):
return PreservedScalarString(s.replace('\r\n', '\n').replace('\r', '\n'))
def walk_tree(base):
if isinstance(base, MutableMapping):
for k in base:
v = base[k] # type: Text
if isinstance(v, string_types):
if '\n' in v:
base[k] = preserve_literal(v)
elif '${' in v or ':' in v:
base[k] = SingleQuotedScalarString(v)
else:
walk_tree(v)
elif isinstance(base, MutableSequence):
for idx, elem in enumerate(base):
if isinstance(elem, string_types):
if '\n' in elem:
base[idx] = preserve_literal(elem)
elif '${' in elem or ':' in elem:
base[idx] = SingleQuotedScalarString(elem)
else:
walk_tree(elem)
然后做
walk_tree(datamap)
从 JSON 加载数据后。
对于以上所有内容,您的 Wordpress.yaml
文件中应该只有一行不同。
关于Python YAML 到 JSON 到 YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51914505/
是否可以在 yaml 中存储未转义的 Markdown 文档?我测试过 key:|+ markdown text block that could have any combination o
在解析使用两个空格缩进创建的 YAML(使用 Ruby 2.5/Psych)时,我看到了奇怪的行为。同一个文件,每行缩进四个空格 - 在我看来 - 正如预期的那样。 两个空格: windows:
如何在 yaml 文件中使用三元运算符让 snakeparser 解析它 我使用 groovy 来解析表达式,!e 标签帮助我这样做。现在,当我使用三元运算符时,解析器会失败。 name : abc
是否可以有这样的多行键? mykey: - > key one: keytwo: val 其中 keyone 被视为一个键。我想解析 yaml 以产生: { mykey:
我有一个 YAML 文件,它有几个不同的键,我想为其提供相同的值。此外,我希望该值易于配置。 请参阅下面的 YAML 以了解我的特定用例: --- # Options for attribute_va
在 Perl 中,我可以执行以下操作: my $home = "/home"; my $alice = "$home/alice"; 我可以在 YAML 中执行以下操作: Home: /home Al
如何在 YAML 中表示空字典? IE。它在语义上应该等同于空的 json-object {}。 最佳答案 简短回答:使用 {} 在 yaml 中有两种表示映射(字典)的方法; flow mappin
我需要根据 if 条件再添加一个名称。如果另一个 .yml 文件中的变量值为“yes”,则在列表中添加新名称 我的 yaml 文件中有以下代码: JsNames: - name: 'jquery.m
我是 yaml 新手,我对用于多行的管道符号 (|) 有疑问。 YAML 是否有类似下面的语法? test: |6+ 在下面的两个 YAML 文件中,第一个有效,第二个无效。我不知道是什么原因造成的。
关于 YAML specs关于问号有2.11段: A question mark and space (“? ”) indicate a complex mapping key. Within a b
1。摘要 我找不到如何自动美化我的 YAML 文件。 2。数据 示例: 我有 SashaPrettifyYAML.yaml 文件: sasha_commands: # Sasha comm
我试图理解 YAML 的基本概念。我没有找到任何相关文档可以消除我的疑虑。例如: product: - sku : BL394D quantity : 4
1。摘要 我找不到如何自动美化我的 YAML 文件。 2。数据 示例: 我有 SashaPrettifyYAML.yaml 文件: sasha_commands: # Sasha comm
是否有在 YAML 键中使用空格的正确方法?喜欢 a test: "hello world!" 或 "a test": "hello world!" 或者这只是一个坏主意,应该使用 a_test: "
我在 YAML 中遇到这个问题通过 perl 使用时。谁能告诉我哪里出了问题。 我有一个代码片段 use YAML; ... my $ifdef_struct = YAML::Load(': unde
我有一系列 OpenCv 生成的 YAML 文件,想用 yaml-cpp 解析它们 我在简单的事情上做得很好,但矩阵表示很困难。 # Center of table tableCenter: !!op
有没有办法在启动文件期间加载的 ROS yaml 文件中使用环境变量? 例如, 测试启动: 例子.yaml: vehicle_name: "${VEHICLE_NAME}_robot
Pandoc 支持 YAML metadata block在 Markdown 文档中。这可以设置标题和作者等。它还可以通过更改字体大小、边距宽度和赋予包含的图形的框架大小来操纵 PDF 输出的外观。
我使用当前(2013/12/12)最新版本的 yaml-cpp。 我注意到 YAML::Load("")和 YAML::Load("---\n...") 导致 Null 节点,即 YAML::Load
我喜欢 YAML。 等等,让我备份。我喜欢看起来像这样的 YAML,甚至比 JSON 还要多: Projects: C/C++ Libraries: - libyaml # "C"
我是一名优秀的程序员,十分优秀!