简体   繁体   中英

Creating a composite string sourced from multiple places in a JSON document

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM