Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 790
eventhorizon Avatar asked Apr 12 '18 09:04

eventhorizon


People also ask

Can JSON be single value?

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 .

How do I convert a JSON to a string?

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.

Can you parse JSON in Bash?

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.

What is jq in Bash?

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.


2 Answers

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
like image 121
eventhorizon Avatar answered Sep 23 '22 08:09

eventhorizon


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
like image 42
Jeff Mercado Avatar answered Sep 20 '22 08:09

Jeff Mercado