【问题标题】:extract value from subarray or return null using jq从子数组中提取值或使用 jq 返回 null
【发布时间】:2019-06-15 23:37:38
【问题描述】:

所以给定这个输入

{
    "id": 1,
    "tags": [
        {
            "Key": "Name",
            "Value": "I am id 1"
        },
        {
            "Key": "Else",
            "Value": "Random"
        }
    ]
}
{
    "id": 2,
    "tags": null
}

我想获取idname 的值(如果存在)。所以对于那个输入,我想得到以下输出。

{
  "id": 1,
  "name": "I am id 1"
}
{
  "id": 2,
  "name": null
}

我试过了:

jq '{"id": .id, "name": .tags[]|select(.Key=="Name").Value}'

但是虽然它在该键存在时提取,但当路径不存在时它无法提供null 或默认值。

你知道如何解决这个问题吗?

你可以试试这个jqplay:https://jqplay.org/s/GgXZg67o79

【问题讨论】:

    标签: json command-line jq


    【解决方案1】:

    使用 jq 1.5 或更高版本

    {id, name: (.tags | if . then from_entries.Name else . end )}
    

    或者,如果您有足够新的(1.6 后)版本的 jq,您可以省略 else .

    {id, name: (.tags | if . then from_entries.Name end )}
    

    jq 1.3 及更高版本的替代方案

    {id, name: (.tags // {} | .[] | select(.Key=="Name").Value // null)}
    

    另请参阅下面的评论。

    【讨论】:

    • {id, name: (.tags | if . then .[] | select(.Key=="Name").Value else null end)} 工作。感谢您的见解@peak!即使没有完整的解决方案,我是否可以接受您的回答?
    • 你用的是什么版本的jq?
    • 我使用的是 jq-1.5
    • 我已经用 jq 1.5 和 jq 1.6 测试了 from_entries 版本。查看早期版本的更新。
    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多