使用 JQ 将长 HTML 文件插入到 Json 文件
Inserting a long HTML file to a Json file using JQ
我正在尝试使用我在此
上找到的命令将一个长 html 文件的内容插入到我的 json 文件中
我使用此命令是因为其他命令仅用于简短参数,而在我的用例中,html 内容可能很长。
jq --slurpfile texts <(jq -Rs file.html) '.body=$texts[0]' file.json >newfile.json
但是,我遇到了这个错误
jq: error: file/0 is not defined at <top-level>, line 1:
file.html
jq: 1 compile error
html 文件的内容似乎无关紧要。我试过只使用一个简单的 html 文件,像这样
<html>
<body></body>
</html>
仍然出现同样的错误。
顺便说一句,在我执行 jq 命令之前,我使用 sed 's/&/\&/g; s/"/\\"/g; s/'"'"'/\\'"'"'/g'
将 html 文件设为编码字符串,如我链接的同一问题中所述
我到底做错了什么?错误信息除此之外什么也没说,所以我不知道出了什么问题
感谢任何帮助
您在内部 jq 调用中缺少过滤器。插入 identity filter .
如 jq -Rs . file.html
:
jq --slurpfile texts <(jq -Rs . file.html) '.body=$texts[0]' file.json >newfile.json
补充说明:
您也可以使用 --argfile
而不是 --slurpfile
,它给您字符串本身而不是数组,您不必再从中提取第一个元素 .[0]
:
jq --argfile texts <(jq -Rs . file.html) '.body=$texts' file.json >newfile.json
此外,如果您使用的是 jq 1.6,还有一种更简单的方法。使用 --rawfile
而不是 --argfile
或 --slurpfile
并且您根本不需要其他 jq 了:
jq --rawfile texts file.html '.body=$texts' file.json >newfile.json
我正在尝试使用我在此
我使用此命令是因为其他命令仅用于简短参数,而在我的用例中,html 内容可能很长。
jq --slurpfile texts <(jq -Rs file.html) '.body=$texts[0]' file.json >newfile.json
但是,我遇到了这个错误
jq: error: file/0 is not defined at <top-level>, line 1:
file.html
jq: 1 compile error
html 文件的内容似乎无关紧要。我试过只使用一个简单的 html 文件,像这样
<html>
<body></body>
</html>
仍然出现同样的错误。
顺便说一句,在我执行 jq 命令之前,我使用 sed 's/&/\&/g; s/"/\\"/g; s/'"'"'/\\'"'"'/g'
将 html 文件设为编码字符串,如我链接的同一问题中所述
我到底做错了什么?错误信息除此之外什么也没说,所以我不知道出了什么问题
感谢任何帮助
您在内部 jq 调用中缺少过滤器。插入 identity filter .
如 jq -Rs . file.html
:
jq --slurpfile texts <(jq -Rs . file.html) '.body=$texts[0]' file.json >newfile.json
补充说明:
您也可以使用 --argfile
而不是 --slurpfile
,它给您字符串本身而不是数组,您不必再从中提取第一个元素 .[0]
:
jq --argfile texts <(jq -Rs . file.html) '.body=$texts' file.json >newfile.json
此外,如果您使用的是 jq 1.6,还有一种更简单的方法。使用 --rawfile
而不是 --argfile
或 --slurpfile
并且您根本不需要其他 jq 了:
jq --rawfile texts file.html '.body=$texts' file.json >newfile.json