Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 963
Maciek Rek Avatar asked Nov 03 '17 22:11

Maciek Rek


People also ask

Can jq write JSON?

jq is an amazing little command line utility for working with JSON data.

What does jq do in bash?

jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.

How do you remove quotes from jq output?

If you want to strip the quotes, just pipe the output from this command to tr -d '"' .


2 Answers

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

jq '.key' <<< "$json_data"
like image 106
jq170727 Avatar answered Oct 26 '22 00:10

jq170727


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"
like image 25
peak Avatar answered Oct 26 '22 00:10

peak