Consider this JSON document
echo '
{
"alpha": {
"id": "id1",
"values": [
"one",
"two"
]
},
"beta": {
"id": "id2",
"values": [
"three"
]
}
}
' >data.json
check syntax
$ yq -p json -P -o j 'true ' data.json
true
I want to generate a series of strings that combines the id
field with each of the values
. So output I need should look like this
"id1-one"
"id1-two"
"id2-three"
This is what I've tried
$ yq -p json -P -o j '.[] | .id as $ID | .values[] | $ID + "-" + . ' data.json
"id1-one"
"id2-one"
"id1-two"
"id2-two"
"id1-three"
"id2-three"
There seems to be a multiplication factor kicking in with the $ID
variable. Is this the correct approach to get attributes from a different scope, or is there a cleaner way to achieve this?
Note -- the real JSON document contains a lot more nesting, so there are multiple nested arrays/objects between the values
and the id
attributes.
One final point. I tried the same code with jq
and it worked fine.
$ jq ' .[] | .id as $ID | .values[] | $ID + "-" + . ' data.json
"id1-one"
"id1-two"
"id2-three"
Do you need that variable elsewhere? Because it just works without:
yq -p json -P -o json '.[] | .id + "-" + .values[]' data.json
"id1-one"
"id1-two"
"id2-three"
Tested with mikefarah/yq version v4.30.5