exonyz
exonyz

Reputation: 61

How to parse JSON with keys from a BASH variable using jq?

I have a JSON array in this format

{
  "id": 707860,
  "name": "Hurzuf",
  "country": "UA",
  "coord": {
    "lon": 34.283333,
    "lat": 44.549999
  }
}

I am using jq to parse it. I'm trying to extract the values of only the keys which are provided in a BASH variable. I tried this with one key in the variable and it works.

KEY=id
jq -r --arg key $KEY '.[] | .[$key]'

However when I tried the same with KEY=coord.lat the output is null and I'm stumped when the number of keys isn't a given.

For example, if the variable is

KEYS=id,name

then the output should be

707860,"Hurzuf"

or, if the variable is

KEYS=coord.lon,coord.lat

then the output should be

 34.283333,44.549999

How can this be done?

Upvotes: 1

Views: 869

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

Split $key into individual paths and convert each to a format getpath could understand. Then you can collect values they point to in an array and join them by commas.

For example, if it's guaranteed that no single path component contain a dot character, something like this should work fine:

[getpath(($key / ",")[] / ".")] | join(",")
$ KEYS=id,coord.lon,coord.lat
$ jq -r '[getpath(($key / ",")[] / ".")] | join(",")' file --arg key "$KEYS"
707860,34.283333,44.549999

Upvotes: 1

Related Questions