Use json path as string variable in jq

I have a tiny example:

  "a": {
    "b": "aaa",
    "c": ""
  "d": "bbb"

And I trying to get the value from a.b and this json path is from string.

I am trying to do as:

$ echo '{"a": {"b": "aaa", "c": ""}, "d": "bbb"}'  | jq '"a.b" as $key | .[$key]'

I don’t know how to.

>Solution :

You can split the path string by the dots to get a path array, which you can use with getpath:

jq -r '"a.b" as $key | getpath($key / ".")'


Note that this works for object fields. If you want it to also work with array indices, you’d need to convert digits to numbers (using tonumber), and come up with a solution how to disambiguate field names that only consist of (stringified) numbers.

Leave a Reply