Home > Enterprise >  Use json path as string variable in jq
Use json path as string variable in jq

Time:11-09

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]'
null

I don't know how to.

CodePudding user response:

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 / ".")'
aaa

Demo

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.

  • Related