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

Stack Overflow Asked on January 5, 2022

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.

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

Polygons from line segments

3  Asked on November 27, 2021


JSLint: Disallow state. in Redux connect functon

0  Asked on November 27, 2021 by hakunin


Copy content of SQL Server 2016 db

4  Asked on November 27, 2021 by mjpolak


How to disable autofix for specific rules in eslint using CLI?

2  Asked on November 27, 2021 by chevybow


Managing multiple sites on XAMPP

1  Asked on November 27, 2021 by moeez


How to find what library provides the import?

1  Asked on November 27, 2021 by daneel-yaitskov


Wait for forEach with a promise inside to finish

2  Asked on November 27, 2021 by inbahn


Solving modular linear congruences for large numbers

2  Asked on November 27, 2021 by oppressionslayer


Sort 3D eigenvector array using eigenvalues

1  Asked on November 27, 2021 by t-a


Interpolation of values from list

3  Asked on November 27, 2021


How can I delete a specific character from set of tuples?

2  Asked on November 27, 2021 by determindedelixir


Ask a Question

Get help from others!

© 2023 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP