motionsickness
motionsickness

Reputation: 187

How to insert quotes in jq string interpolation in bash

I'm tying to use jq to make to exportable variables in bash. I ran in to an issue with strings that contain spaces. I tried modifying my jq but all I get are invalid character errors. I have tried both single quotes or double quotes but neither have worked for me. What am I missing here?

input:

{
   "PD_TOKEN":"Token y_NbAkKc66ryYTWUXYEu",
   "API":"http://cool.api/",
   "HELP_URL":"https://help.com"
}

jq:

jq -r 'to_entries|map("\(.key)=\(.value|tostring)")' /json

current result:

PD_TOKEN=Token y_NbAkKc66ryYTWUXYEu

wanted result (note the quotation marks):

PD_TOKEN="Token y_NbAkKc66ryYTWUXYEu"

Upvotes: 4

Views: 3435

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52152

You can use @sh instead of tostring to escape shell-safely:

$ jq -r 'to_entries | map("\(.key)=\(.value|@sh)")[]' infile.json
PD_TOKEN='Token y_NbAkKc66ryYTWUXYEu'
API='http://cool.api/'
HELP_URL='https://help.com'

Additionally, without map:

  • Using the array iterator in the first step (h/tip oguz ismail):

    jq -r 'to_entries[] | "\(.key)=\(.value|@sh)"' infile.json
    
  • Iterate over keys (h/tip ikegami):

    jq -r 'keys[] as $key | "\($key)=\(.[$key]|@sh)"' infile.json
    

Upvotes: 10

Related Questions