Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading