首页 > 解决方案 > 使用 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(&#39;code blocks can be a pain&#39;);
}
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,或者是否有更好的方法?

标签: bashshellcurlhtml-parsing

解决方案


我将使用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(&#39;code blocks can be a pain&#39;);\n}\ngo();\n</code>\n</pre>"
      }
    }

$(< filename)bash计算给定文件内容的替换。它比$(cat filename)in更受欢迎,bash因为它不涉及运行另一个进程。


推荐阅读