'File content to single JSON string value with bash
I would like to read a file and put the whole content into a single string that is escaped to be used in a JSON object.
And I want to do it on the commandline/terminal (Linux).
Solution 1:[1]
Version 1
WARNING: With this solution the content of the file can be too big to fit in an argument!
jq -n \
--arg content "$(cat theFile.txt)" \
'{ theContent : $content }' \
| \
jq '.theContent'
Version 2
Jeff Mercado provided a more compact solution for the first part - so I adapted that in my code as follows:
jq -Rs \
'{ theContent: . }' \
theFile.txt \
| \
jq '.theContent'
Version 3
Now Jeff Mercado provided a more compact solution for what I was looking for:
jq -Rs '.' theFile.txt
Solution 2:[2]
A more direct way to do that is to use the raw input (-R) combined with slurp (-s) parameters to read the entire input as a single string. Then take that input and store in the appropriate property. You don't need to pass it in as a separate parameter.
$ jq -Rs '{ theContent: . }' theFile.txt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jeff Mercado |
