在 yq 中使用 json 格式的外部输入更新 YAML 文件
我有一个 in.yaml 文件,其中包含
name: test
我想要在 yaml 文件中动态创建数组内容的内容。我使用 yq 和要添加的元素的 json 编码,但是当我以字符串形式提供内容时,不会附加元素。
考虑代码:
entry='[{"name":"mango","color":"yellow"}]'
ENTRY=$entry yq e '."details"=strenv(ENTRY)' in.yaml
输出:
name: test
details: '[{"name":"mango","color":"yellow"}]'
以下内容有效,但不会让我通过其他属性传递条目。
yq e '."details"=[{"name":"mango","color":"yellow"}]' in.yaml
输出:
name: test
details:
- name: mango
color: yellow
- name: apple
color: red
我使用的这个不正确或者不受支持?
I have a file in.yaml with the content
name: test
I want to create dynamically content of an array in a yaml file. I am using yq and an json encoding of the element to be added, but when I provide the content as a string the elements are not appended.
Consider the code:
entry='[{"name":"mango","color":"yellow"}]'
ENTRY=$entry yq e '."details"=strenv(ENTRY)' in.yaml
Output:
name: test
details: '[{"name":"mango","color":"yellow"}]'
The following works, but does not make me pass the entry via an other attribute.
yq e '."details"=[{"name":"mango","color":"yellow"}]' in.yaml
Output:
name: test
details:
- name: mango
color: yellow
- name: apple
color: red
I am using this incorrect or is this not supported?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当
strenv
将变量的内容转换为文字字符串时,请使用from_json
再次对其进行解码。然后,使用... style=""
将引用样式重置为空(在键和值中),以匹配您所需的输出样式:或者,首先避免初始转换通过将
strenv
更改为env
,这样输入就可以直接解释为 YAML(JSON 是 YAML 的子集)。不过,您仍然需要重置引用样式:As
strenv
converts the variable's contents into a literal string, usefrom_json
to decode it again. Then, reset the quoting style to empty (in both, keys and values) using... style=""
in order to match your desired output style:Alternatively, avoid the initial conversion in the first place by changing
strenv
to justenv
, so the input can be directly interpreted as YAML (JSON is a subset of YAML). You'd still need to reset the quoting style, though: