使用bash将文件内容转换为单个JSON字符串值 [英] File content to single JSON string value with bash
本文介绍了使用bash将文件内容转换为单个JSON字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取一个文件,然后将整个内容放入一个字符串中,然后转义以用于JSON对象。
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.
我想做
推荐答案
版本1
Version 1
jq -n \
--arg content "$(cat theFile.txt)" \
'{ theContent : $content }' \
| \
jq '.theContent'
版本2
Jeff Mercado 为第一部分提供了更紧凑的解决方案-因此我在我的代码如下:
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'
版本3
现在 Jeff Mercado 为我寻找的东西提供了更紧凑的解决方案:
Version 3
Now Jeff Mercado provided a more compact solution for what I was looking for:
jq -Rs '.' theFile.txt
这篇关于使用bash将文件内容转换为单个JSON字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文