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
If you're trying to do this in a
.sh
file, this is what worked for me:I would suggest using a bash here string. e.g.
Use the bash:
echo "$json_data" | jq '.key'
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:
env
If the shell variable is not aleady an environment variable:
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:
If you want to use inline command, I found this work on my Mac: