简体   繁体   中英

how to combine a value with each of the element of another array in a JSON using jq?

The JSON like this:

[
  {
    "id": 1,
    "names": [
      "apple",
      "google"
    ]
  },
  {
    "id": 2,
    "names": [
      "iphone",
      "ipad",
      "macbook"
    ]
  }
]

expected output in tsv

1 apple
1 google
2 iphone
2 ipad
2 macbook

You can use map

along with raw-output option such as

jq -r 'map( "\(.id) " + .names[] )[]'

Demo

or formatting as tsv :

jq -r 'map( "\(.id) " + .names[] ) | @tsv'

which outputs the result on a single line

Demo

or use

jq -r 'map( "\(.id)\t" + .names[])[]'

in order to get tab-delimited results between attributes while returning each combinations on separate lines

Demo

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