jq 用于构建复杂的 json 参数

在使用 curl 来构建 post 的数据时,有可能参数是通过读取文件的内容来得到的,而数据可能需要被构建成 json 的格式,这可能会很复杂。一是 json 中有大量的双引号需要区隔,二是被读取的文件中的内容可能有很多行需要与命令本身的换行和空格区隔,该如何做呢,有没有自动的换行符等的处理?答案是有的,可以用 jq 工具。

--rawfile 选项可用于读取指定文件的内容并指定到 jq 的指定变量。

--arg 则是直接指定变量的值。

-n 则可以在参数定义的模板中直接使用上述定义的指定变量,如 $remark 使用了上述定义的变量 remark

--null-input/-n:
Don´t parse the input as JSON. Instead, each line of text is passed to  the  filter as a string.

用例如:

jq -n \
    --rawfile cert "/etc/hosts" \
    --arg remark "post using curl command" \
    '{remark: $remark, body: $cert}'

就能得到期望中的 json 数据。

再如:

jq -n \
    --rawfile cert "/etc/hosts" \
    --arg remark "post using curl command" \
    '{remark: $remark, body: $cert}' \
| curl "http://localhost" -H "content-type:application/json" -d @-

则可以利用 curl@- 符号将构建好的 body 参数(来自于 stdin)给 curl

If  you  start  the data with the letter @, the rest should be a
file name to read the data from, or - if you want curl  to  read
the data from stdin.

(文末尾,谢谢阅读)

关于本文如您有任何想法和意见,欢迎与我们联系,邮箱地址zhi@uqugu.com
您对本文有什么看法,喜欢或者不喜欢都可以发表意见。