1

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?

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@exonyz Then your input is an array. jq -r '.[] | [getpath... will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.