tres.14159
tres.14159

Reputation: 920

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

I don't know how to.

Upvotes: 0

Views: 431

Answers (1)

pmf
pmf

Reputation: 36151

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.

Upvotes: 1

Related Questions