发送未序列化的&使用bash脚本将未转义的HTML文件数据传输到API [英] Send unserialized & unescaped HTML file data to an API with a bash script

查看:58
本文介绍了发送未序列化的&使用bash脚本将未转义的HTML文件数据传输到API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个bash脚本,该脚本需要一个HTML文件并将其发送到多个API.

I wanted to create a bash script that takes an HTML file and sends it to several APIs.

我有一个 test.html 文件,其中包含未序列化的HTML数据,如下所示:

I have a test.html file with unserialized HTML data like this:

<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,如下所示:

I need to send the content of the file somehow to an API, like this:

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

The only way I can think of so far, is to serialize/escape the HTML file, reading it into a variable as a string (like $TEST_HTML=$(cat serialized_test.html) and then passing it to "body_markdown".

是否可以在bash脚本中一步实现序列化/转义HTML,还是有更好的方法?

Would it be possible to serialize/escape the HTML in one step inside the bash script or is there maybe a better way?

推荐答案

我将使用 jq 构建JSON参数,并使其包含的引号,换行符等正确转义.HTML文件:

I'd use jq to build the JSON argument, and let it deal with properly escaping quotes, newlines and such in the included HTML file:

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 中,并计算为:

The jq invocation puts the contents of test.html in a string variable $html, and evaluates to:

    {
      "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 的替换,其结果为给定文件的内容.它比 bash 中的 $(cat文件名)更可取,因为它不涉及运行其他进程.


$(< filename) is a bash substitution that evaluates to the contents of the given file. It's to be preferred over $(cat filename) in bash as it doesn't involve running another process.

这篇关于发送未序列化的&amp;使用bash脚本将未转义的HTML文件数据传输到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆