jq保留捕获组和更新阵列中缺少的数组对象 [英] jq retain missing array objects from capturing group and update array

查看:134
本文介绍了jq保留捕获组和更新阵列中缺少的数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


输入



[{
        "tags": [{
                "value": "domain:sourcing"
            },
            {
                "value": "apiname:src1"
            }
        ]
    },
    {
        "tags": [{
            "value": "apiname:fin1"
        }]
    },
    {
        "tags": [{
            "value": "domain:fin1"
        }]
    }
]




预期输出



[{
        "domain": "sourcing",
        "apiname": "src1"
    },
    {
        "domain": "-",
        "apiname": "fin1"
    },
    {
        "domain": "fin1",
        "apiname": "-"
    }
]

到目前为止,我在下面尝试过。

So far I have tried below.

jq'map(。+(.tags [ ] .value | capture(domain:(?< domain>。+))))| map(。+(。tags []。value | capture(apiname:(?< apiname>。+))))| map(del(.tags))'


以上cmd的部分输出



[
  {
    "apiDomain": "sourcing",
    "apiName": "src1"
  }
]

正如您所看到的,这里的问题是如果没有任何一个捕获组提交,我将完全失去其他对象。输入中的第二个对象具有 apiname 但缺少domain,第三个对象具有domain但缺少apiname。如示例输出中所述,如果没有任何对象,则它们应该为 -

As you have seen, the problem here is I'm completely loosing the other objects if any one capturing group filed is absent. Second object in input has apiname but missing "domain" and third object has "domain" but missing "apiname". As stated in the sample output, if any object doesn't present, then they should come as "-".

jq命令是否可以请更新以实现此目的吗?

Can the jq command be updated to achieve this please?

推荐答案

如果tag:value字符串的value部分可能包含冒号(:),然后使用 split 变得不必要地棘手(甚至可能效率低下),因此使用捕获,或许与@RomanPerekhrest建议的一致:

If the "value" part of the "tag:value" strings might contain a colon (":"), then using split becomes unnecessarily tricky (and maybe even inefficient), so it might be easier to use capture, perhaps along the lines suggested by @RomanPerekhrest:

{domain:"-", apiname:"-"} as $default
| map([.tags[].value
       | capture("(?<k>[^:]*):(?<v>.*)")
       | {(.k): .v} ]
      | add
      | $default + .)

这篇关于jq保留捕获组和更新阵列中缺少的数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆