27

I am trying to load a JSON file using jq per here. It is quite straightforward and this works:

$ cat ~/Downloads/json.txt | jq '.name'
"web"

However, I need to assign the output of this variable to a command. I tried to do this and this works:

$ my_json=`cat ~/Downloads/json.txt | jq '.name'`
$ myfile=~/Downloads/$my_json.txt
$ echo $myfile
/home/qut/Downloads/"web".txt

But I want /home/qut/Downloads/web.txt.

How do I remove the quotes, i.e. change "web" to web?

muru
  • 193,181
  • 53
  • 473
  • 722
edesz
  • 763
  • 3
  • 11
  • 19

4 Answers4

47

You can use the tr command to remove the quotes:

my_json=$(cat ~/Downloads/json.txt | jq '.name' | tr -d \")
Florian Diesch
  • 86,013
  • 17
  • 224
  • 214
  • 2
    Thank you for the `tr` command... I looked through 4 different posts with hundreds of upvotes with people writing 40+ character mega-one-liners to get the job done. You have the correct (and probably modern) solution. – Shadoninja Jun 11 '18 at 15:04
28

In the particular case of jq, you can specify that the output should be in raw format:

   --raw-output / -r:

   With this option, if the filter´s result is a string then  it  will
   be  written directly to standard output rather than being formatted
   as a JSON string with quotes. This can be useful for making jq fil‐
   ters talk to non-JSON-based systems.

To illustrate using the sample json.txt file from your link:

$ jq '.name' json.txt
"Google"

whereas

$ jq -r '.name' json.txt
Google
steeldriver
  • 131,985
  • 21
  • 239
  • 326
1

There's more simple and efficient, using the native shell prefix/suffix removal feature:

my_json=$(cat ~/Downloads/json.txt | jq '.name')
    temp="${my_json%\"}"
    temp="${temp#\"}"
    echo "$temp"

Source https://stackoverflow.com/questions/9733338/shell-script-remove-first-and-last-quote-from-a-variable

Agnel Vishal
  • 113
  • 5
1

You could use eval echo like this:

my_json=$(eval echo $(cat ~/Downloads/json.txt | jq '.name'))

but this is not ideal - could easily cause bugs and/or security flaws.

wjandrea
  • 14,109
  • 4
  • 48
  • 98