skip to Main Content

I have a JSON structure that looks like this, it’s essentially a bash shell command stored in JSON. Is there a way in jq to map this data back to multiline string ?

[
  "newcert \n",
  "    --cn server1.acme.com \n",
  "    --san-dns server1.acme.com \n",
  "    --key-file ./config/key.pem \n",
  "    --csr-file ./config/csr.pem \n",
  "    --no-prompt \n"
]

I need to map it back to a string that looks like this:

  newcert 
      --cn server1.acme.com 
      --san-dns server1.acme.com 
      --key-file ./config/key.pem 
      --csr-file ./config/csr.pem 
      --no-prompt 

3

Answers


  1. jq has a join function:

    cmd=$(jq -r '. | join("")' data.json)
    
    # To execute it
    eval $cmd
    

    Standard security warning about eval: they can execute any command, so make sure you trust the input source.

    Login or Signup to reply.
  2. Just run add on the array, use -r for raw output (i.e. no escapes):

    jq -r 'add' file.json
    
    Login or Signup to reply.
  3. As the lines already contain their newline symbols, you could instruct jq to omit its owns by using the -j option:

    jq -j '.[]' file.json
    
    newcert 
        --cn server1.acme.com 
        --san-dns server1.acme.com 
        --key-file ./config/key.pem 
        --csr-file ./config/csr.pem 
        --no-prompt 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search