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).
JSON data, at its simplest, can be a single object composed of fields, with each field having a simple value. Some terminology: A value can be a simple value, an array, or an object. A simple value can be a string, a number, or a Boolean value true or false , or null .
Stringify a JavaScript Object const obj = {name: "John", age: 30, city: "New York"}; Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
By default shells like Bash do not have a standard JSON parser included. You would either have to drop into a programming language interpreter or install a small dedicated utility.
jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.
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'
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'
Now Jeff Mercado provided a more compact solution for what I was looking for:
jq -Rs '.' theFile.txt
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With