Input
[{
\"tags\": [{
\"value\": \"domain:sourcing\"
},
{
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
solution:
jq '{domain: "-", apiname: "-"} as $o
| map([.tags[] | .value | split(":") | {(.[0]) : .[1]}] | add | $o + .)' input.json
{domain: "-", apiname: "-"} as $o
- used as a template objectThe output:
[
{
"domain": "sourcing",
"apiname": "src1"
},
{
"domain": "-",
"apiname": "fin1"
},
{
"domain": "fin1",
"apiname": "-"
}
]
Here's another approach. This assumes your tags
array will only contain the names you expect.
map(
reduce (.tags[].value | split(":")) as [$k,$v] (
{domain:"-",apiname:"-"};
.[$k] = $v
)
)
For a more general solution that doesn't assume fixed names and just flattens the tags, I'd do this:
map(
reduce (.tags[].value | split(":")) as [$k,$v] (
del(.tags);
.[$k] = $v
)
)
Then as you access the fields, just use the alternative operator to set the default value.
(.domain // "-") as $domain