7

Here is the example json

{
   "app": "K8s",
   "version": "1.8",
   "date": "2018-10-10"
}

In order to get the value of app, I can do this in jq as

jq '.app'

But what I want is, I want to pass the key to jq as a bash variable, i.e

bash_var="app"
jq '."${bash_var}"'

I'm getting the output as null instead of the value. What is the correct syntax to achieve this?

Sagar Zala
  • 4,854
  • 9
  • 34
  • 62
k_vishwanath
  • 1,326
  • 2
  • 20
  • 28
  • @BenjaminW/tripleee.: I would have closed it a duplicate, if not for the 2nd part of the question, that involves using the variable as the key. I think that warrants the need for the question to be unique – Inian Oct 10 '18 at 04:16
  • We do have existing duplicates covering the key case specifically, though (or at least, covering failures that take place with naive solutions). Let me hunt around... – Charles Duffy Oct 10 '18 at 04:18
  • ...ahh, what I was thinking of was https://stackoverflow.com/questions/52562653/invalid-numeric-literal-error-from-jq-trying-to-modify-json-with-variable/52562738#52562738 – Charles Duffy Oct 10 '18 at 04:19
  • So the question is in parts duplicate to [Passing bash variable to jq select](https://stackoverflow.com/questions/40027395/passing-bash-variable-to-jq-select) and [“Invalid numeric literal” error from jq trying to modify JSON with variable](https://stackoverflow.com/q/52562653/5291015), but not completely – Inian Oct 10 '18 at 04:23

1 Answers1

31

First, you need to port the bash variable into jq's context usign the --arg flag and access it inside the [..]

jq --arg keyvar "$bash_var" '.[$keyvar]' json
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 2
    I do not think you have to port the `bash` variable to `jq`'s context. You can simply achieve the goal by following: `jq ".$bash_var"` – Jaroslav Bezděk Jul 17 '19 at 11:09
  • 6
    @JaroslavBezděk: That can easily break when $bash_var contains `"` or any other character interpreted by `jq`. – choroba Aug 12 '20 at 09:50