Can I pass a string variable to jq not the file?

JsonBashVariablesInputJq

Json Problem Overview


I want to convert JSON string into an array in bash. The JSON string is passed to the bash script as an argument (it doesn't exist in a file).

Is there a way of achieving it without using some temp files?

Similarly to this:

script.sh

#! /bin/bash
json_data='{"key":"value"}'
jq '.key' $json_data

jq: error: Could not open file {key:value}: No such file or directory

Json Solutions


Solution 1 - Json

I would suggest using a bash here string. e.g.

jq '.key' <<< "$json_data"

Solution 2 - Json

The value of the variable "json_data" that was given in the original question was not valid JSON, so this response still covers both cases (nearly-valid and valid JSON).

Valid JSON

If "$json_data" does hold a valid JSON value, then here are two alternatives not mentioned elsewhere on this page.

--argjson

For example:

 jq -n --argjson data "$json_data" '$data.key'
env

If the shell variable is not aleady an environment variable:

json_data="$json_data" jq -n 'env.json_data | fromjson.key'
Nearly-valid JSON

If indeed $json_data is invalid as JSON but valid as a jq expression, then you could adopt the tactic illustrated by the following transcript:

$ json_data='{key:"value"}'
$ jq -n "$json_data" | jq .key
"value"

Solution 3 - Json

Use the bash: echo "$json_data" | jq '.key'

Solution 4 - Json

Absolutely. Just tell bash to http://tldp.org/LDP/abs/html/process-sub.html">give it a file instead.

jq '.key' <(echo "$json_data")

And make sure you run it in bash, not sh.

Solution 5 - Json

If you want to use inline command, I found this work on my Mac:

echo '{"key":"value"}' | jq .key

Solution 6 - Json

#! /bin/bash
json_data='{"key":"value"}'
echo $json_data | jq --raw-output '.key'

Solution 7 - Json

If you're trying to do this in a .sh file, this is what worked for me:

local json_data $(getJiraIssue "$1")               # store JSON in var
echo `jq -n "$json_data" | jq '.fields.summary'`   # pass that JSON var to jq

Solution 8 - Json

Just do

$ jq '.key' <<< $'{"key":"value"}'
"value"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaciek RekView Question on Stackoverflow
Solution 1 - Jsonjq170727View Answer on Stackoverflow
Solution 2 - JsonpeakView Answer on Stackoverflow
Solution 3 - JsonJavierView Answer on Stackoverflow
Solution 4 - JsonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 5 - JsonAbigail NguyenView Answer on Stackoverflow
Solution 6 - JsonSupun MadushankaView Answer on Stackoverflow
Solution 7 - JsonWesley SmithView Answer on Stackoverflow
Solution 8 - JsonLogan LeeView Answer on Stackoverflow