bash - 使用 bash 脚本将未序列化和未转义的 HTML 文件数据发送到 API
问题描述
我想创建一个 bash 脚本,它接收一个 HTML 文件并将其发送到多个 API。
我有一个test.html
带有未序列化 HTML 数据的文件,如下所示:
<h2 id="overview">Overview</h2>
<p>Have the source of truth in your own space at <strong>somewhere</strong></p>
<pre>
<code class="lang-javascript">function go() {
console.log('code blocks can be a pain');
}
go();
</code>
</pre>
我需要以某种方式将文件的内容发送到 API,如下所示:
curl --location --request POST 'https://devo.to/api/articles' \
--header 'api-key: askldjfalefjw02ijef02eifj20' \
--header 'Content-Type: application/json' \
--data-raw '{
"article": {
"title": "Blog Article",
"body_markdown": "@test.html",
}
}'
到目前为止,我能想到的唯一方法是序列化/转义 HTML 文件,将其作为字符串(如$TEST_HTML=$(cat serialized_test.html
)读入变量,然后将其传递给"body_markdown"
.
是否可以在 bash 脚本中一步序列化/转义 HTML,或者是否有更好的方法?
解决方案
我将使用jq
构建 JSON 参数,并让它处理包含的 HTML 文件中正确转义的引号、换行符等:
curl --location --request POST 'https://devo.to/api/articles' \
--header 'api-key: askldjfalefjw02ijef02eifj20' \
--header 'Content-Type: application/json' \
--data-raw "$(jq -n --arg html "$(< test.html)" '{article:{title:"Blog Article",body_markdown:$html}}')"
该jq
调用将 的内容test.html
放入字符串变量$html
中,并计算为:
{
"article": {
"title": "Blog Article",
"body_markdown": "<h2 id=\"overview\">Overview</h2>\n<p>Have the source of truth in your own space at <strong>somewhere</strong></p>\n<pre>\n<code class=\"lang-javascript\">function go() {\n console.log('code blocks can be a pain');\n}\ngo();\n</code>\n</pre>"
}
}
$(< filename)
是bash
计算给定文件内容的替换。它比$(cat filename)
in更受欢迎,bash
因为它不涉及运行另一个进程。
推荐阅读
- c# - C#如何正确地将数组中的多个自定义对象反序列化为一个对象?
- java - 如何调试 Java HTTPS 证书验证
- javascript - JS:如何将两个不同数组中的对象组合成一个数组/对象
- heroku - 如何在 Heroku 中制作虚拟网络
- xcode - 在 xib 文件中隐藏主页指示器
- html - 如何在移动设备上将 4 列表拆分为 2 列?
- caching - 清除共享文件以外的 Microsoft Teams 本地缓存?
- javascript - 如何使用以前日期的 Material-UI 禁用表格上的复选框?
- python - 将位掩码转换为字符串列表的最短方法是什么?
- python - 遍历字典并为每个键创建一个对象,其值在同一对象中