You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JQ保留捕获组缺失的数组对象并更新数组?

Correct JQ Code to Transform Tag Arrays to Structured Objects

Hey there, let's fix that JQ code so it properly maps your tag arrays to the desired structure with fallback values for missing fields.

Input JSON

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

Desired Output

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

The Fix

Your initial code struggled because it tried to capture all tag types at once, which breaks when a tag is missing. Instead, we'll use reduce to build each object incrementally with fallback values:

map(
  .tags | reduce .[] as $tag (
    { domain: "-", apiname: "-" };
    $tag.value | capture("(?<key>domain|apiname):(?<value>.+)") |
    .[$captured.key] = $captured.value
  )
)

How This Works

  • We start with a default object where both domain and apiname are set to - (our fallback for missing tags).
  • Using reduce, we loop through each tag in the tags array for every item.
  • For each tag, we capture the key (either domain or apiname) and its corresponding value.
  • We then update the default object's field matching the captured key with the actual value from the tag.
  • This ensures that even if one of the tags is missing, the fallback - remains in place for that field.

Testing It Out

Run this JQ command against your input JSON, and you'll get exactly the structured output you're looking for. The reduce approach is robust here because it handles each tag individually, avoiding the pitfalls of trying to capture missing fields directly.

内容的提问来源于stack exchange,提问作者Naveen K Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:51:52