如何用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
domainandapinameare set to-(our fallback for missing tags). - Using
reduce, we loop through each tag in thetagsarray for every item. - For each tag, we capture the key (either
domainorapiname) 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
相关产品推荐
相关产品推荐

