【问题标题】:How to handle empty string in jqjq中如何处理空字符串
【发布时间】:2020-09-15 18:18:13
【问题描述】:

我有一个这样的 jq 命令:

jq '.SecurityGroups[] | {name: .GroupName, groupid: .GroupId, ips: .IpPermissions[].IpRanges[].CidrIp, sourcegroup: .IpPermissions[].UserIdGroupPairs[].GroupId}'

除了一件事,它运作良好。它似乎无法处理该值不存在的情况。仅当所有值都存在时才返回。

预期输出

{
  "name": "group1",
  "groupid": "sg-012345",
  "ips": "10.0.0.0/8",
  "sourcegroup": ""           # having this value not return at all would suffice
}
{
  "name": "group2",
  "groupid": "sg-06789",
  "ips": "",                  # having this value not return at all would suffice
  "sourcegroup": "sg-abcd"
}
{
  "name": "group3",
  "groupid": "sg-xyz",
  "ips": "192.0.0.0/8",
  "sourcegroup": "sg-xyz"
}

JSON 输入

{
    "SecurityGroups": [
        {
            "GroupName": "group1",
            "IpPermissions": [
                {
                    "IpRanges": [
                        {
                            "CidrIp": "10.0.0.0/8"
                        }
                    ],
                    "UserIdGroupPairs": []
                },
            "GroupId": "sg-012345",
        },
        {
            "GroupName": "group2",
            "IpPermissions": [
                {
                    "IpRanges": [],
                    "UserIdGroupPairs": [
                        {
                            "GroupId": "sg-abcd",
                        }
                    ]
                },
            "GroupId": "sg-06789",
        },
        {
            "GroupName": "group3",
            "IpPermissions": [
                {
                    "IpRanges": [
                        {
                            "CidrIp": "192.0.0.0/8"
                        }
                    ],
                    "UserIdGroupPairs": [
                        {
                            "GroupId": "sg-xyz",
                        }
                    ]
                },
            "GroupId": "sg-xyz"
        }
    ]
}

我发现了以下内容,但我看不到它适用于我的情况,所以不确定我在这里做错了什么:

jq: Remove keys with empty string values

【问题讨论】:

  • 这里的JSON输入无效。

标签: jq


【解决方案1】:

虽然您的 JSON 无效,但您可能可以使用替代运算符 // 来实现您所需要的。这是一个最小的完整示例:

$ jq . test.json
[
  {
    "a": 1,
    "b": [
      {
        "c": 3
      }
    ]
  },
  {
    "a": 2,
    "b": []
  }
]
$ jq '.[] | {aa: .a, bb: .b[].c}' test.json # attempt 1
{
  "aa": 1,
  "bb": 3
}
$ jq '.[] | {aa: .a, bb: (.b[].c // "")}' test.json # attempt 2
{
  "aa": 1,
  "bb": 3
}
{
  "aa": 2,
  "bb": ""
}

您可以看到第二个元素的 b 数组为空,导致在第一次尝试中将其从结果中省略,类似于您的方法。在第二次尝试中,我们使用了替代运算符来合并到空字符串。

可以通过多种方式删除不存在的条目,例如:

$ jq '.[] 
  | {aa: .a, bb: (.b[].c // null)} 
  | if .bb == null then del(.bb) else . end
' test.json
{
  "aa": 1,
  "bb": 3
}
{
  "aa": 2
}

【讨论】:

  • 是的,对无效的 json 感到抱歉。我正在编辑敏感信息,因此可能不小心删除了字符。稍后我会提出您的建议,谢谢您的帮助!
猜你喜欢
  • 2021-07-11
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 2019-11-29
  • 2019-05-03
相关资源
最近更新 更多