File content to single JSON string value with bash

依然范特西╮ 提交于 2020-07-20 11:43:09

问题


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


回答1:


Version 1

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



回答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


来源:https://stackoverflow.com/questions/49793500/file-content-to-single-json-string-value-with-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!