Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import plain text file in to JSON via JQ

Tags:

json

text

import

jq

I have two files:

id_rsa

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

and id_rsa.pub

ssh-rsa AAAAB3NzaC1yc2EAAA...

Using JQ, how can import them into a json file like:

{
  "pem": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----",
  "pub": "ssh-rsa AAAAB3NzaC1yc2EAAA..."
}

I have tried a couple, but it's not working:

jq --null-input --argfile pem id_rsa --argfile pub id_rsa.pub '.pem=$pem | .pub=$pub'
jq: Bad JSON in --argfile pem id_rsa: Invalid numeric literal at line 1, column 11
like image 674
AG6HQ Avatar asked Oct 29 '25 01:10

AG6HQ


1 Answers

Assuming your jq supports the --rawfile command-line option (as does jq 1.6), the simplest would be to use it, e.g.:

jq -Rs --rawfile pub id_rsa.pub '{pem: ., pub: $pub}' id_rsa

The -R flag (aka --raw-input) tells jq not to parse the input as JSON. Each line of text is passed directly to the filter as a string.

The -s flag (aka --slurp) tells jq to read the entire incoming stream at one time. Combined with -R this pulls the entire file into a single variable.

Without --rawfile

jq -Rs --argfile pub <(jq -R '{pub: .}' id_rsa.pub) '{pem: .} + $pub' id_rsa

Trailing newlines

If you want to ensure there is no trailing \n at the end of the strings, then you could add calls to sub("\n$";"") as warranted.

like image 178
peak Avatar answered Oct 30 '25 21:10

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!