Passing a path ("key1.key2") from a bash variable to jq

I am having trouble accessing bash variable inside ‘jq’.
The snippet below shows my bash loop to check for missing keys in a Json file.

for key in "key1" "key2.key3"; do
  echo "$key"
  if ! cat ${JSON_FILE} | jq --arg KEY "$key" -e '.[$KEY]'; then


  "key1": "val1",
  "key2": {
    "key3": "val3"

The script works correctly for top level keys such as "key1". But it does not work correctly (returns null) for "key2.key3".

‘jq’ on the command line does return the correct value

cat input.json | jq '.key2.key3'

I followed answers from other posts to come to this solution. However can’t seem to figure out why it does not work for nested json keys.

Stack Overflow Asked on January 5, 2022

1 Answers

One Answer

Using --arg prevents your data from being incorrectly parsed as syntax. Usually, a shell variable you're passing into jq contains literal data, so this is the correct thing.

In this case, your variable contains syntax, not literal data: The . isn't part of the string you want to do a lookup by, but is instead an instruction to jq to do two separate lookups one after the other.

So, in this case, you should do the more obvious thing, instead of using --arg:

jq -e ".$KEY"

Answered by Charles Duffy on January 5, 2022

Add your own answers!

Related Questions

Cannot append option for select form

1  Asked on November 20, 2021 by nguyn-v


Constructors with the same primitive type as parameter

3  Asked on November 18, 2021 by arjun-singh


Python regex for numbers between 0-63

3  Asked on November 18, 2021 by perplexityy


How can I retrieve many values of a same field in a GET request

2  Asked on November 18, 2021 by user2424634


Can i know why my while loop is not working?

0  Asked on November 18, 2021 by niranjan-kumar


Moment JS days difference issue

1  Asked on November 18, 2021


How to update the value of a prop upon a state change in React

2  Asked on November 18, 2021 by alopez02


reload div without refresh page

1  Asked on November 18, 2021 by kemar-aim


Convert heirachy to dict of lists

0  Asked on November 18, 2021 by himabindu


Ask a Question

Get help from others!

© 2022 All rights reserved.