【发布时间】:2021-02-03 21:45:57
【问题描述】:
考虑这个 JSON 输入:
{
"id":0,
"Tags": [
{"Key":"Name", "Value":"machine1"},
{"Key":"Stage", "Value":"UAT"}
]
},
{
"id":1,
"Tags": [
{"Key":"Stage", "Value":"UAT"}
]
},
{
"id":2,
"Tags": []
},
{
"id":3
}
我寻求一种解决方案,在管道和选择之后将产生Value 字段的值,其中键Name 是Name 或(none) 作为默认值。我得到的最接近的是:
jq -r 'if(.Tags == null or .Tags == []) then .Tags=[{"Key":"Name","Value":"(none)"}] else . end | "\(.id) \(.Tags[] | select(.Key == "Name")|.Value)" '
该解决方案适用于 id 0、2 和 3。当 Tags 数组存在但 不 包含 .Key == "Name" 时,选择会产生 null 并且没有值被退回。如果我再多考虑一下,我可能会偶然发现它,但是。理想情况下,我想做这样的事情(jq 伪代码):
Defend against null tags, then walk array looking for Name
'\(.Tags // [{}] | select(.Tags[].Key == "Name")?.Value // "(none)")
可能只是我确实还需要 1 个阶段,但我想探索其他聪明的可能性。
【问题讨论】:
-
您的示例 JSON 输入似乎无效(我收到
jq: parse error: Expected value before ',' at line 7, column 2)。您的意思是写它时不使用逗号分隔对象吗? -
要解析逗号分隔的 JSON,并在单独的行上分隔逗号,请参阅 jq 常见问题解答(查找:
def iterate(f): def r: f | (., r); r;)
标签: jq