在 yq 中使用 json 格式的外部输入更新 YAML 文件

发布于 2025-01-13 16:47:41 字数 636 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜夜流光相皎洁 2025-01-20 16:47:41

strenv 将变量的内容转换为文字字符串时,请使用 from_json 再次对其进行解码。然后,使用 ... style="" 将引用样式重置为空(在键和值中),以匹配您所需的输出样式:

ENTRY="$entry" yq e '.details=(strenv(ENTRY) | from_json | ... style="")' in.yaml

或者,首先避免初始转换通过将 strenv 更改为 env,这样输入就可以直接解释为 YAML(JSON 是 YAML 的子集)。不过,您仍然需要重置引用样式:

ENTRY="$entry" yq e '.details=(env(ENTRY) | ... style="")' in.yaml

As strenv converts the variable's contents into a literal string, use from_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:

ENTRY="$entry" yq e '.details=(strenv(ENTRY) | from_json | ... style="")' in.yaml

Alternatively, avoid the initial conversion in the first place by changing strenv to just env, 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:

ENTRY="$entry" yq e '.details=(env(ENTRY) | ... style="")' in.yaml
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文