Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass bash variable as a key to jq? [duplicate]

Tags:

bash

shell

jq

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?

like image 390
k_vishwanath Avatar asked Oct 10 '18 04:10

k_vishwanath


1 Answers

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
like image 67
Inian Avatar answered Oct 22 '22 21:10

Inian