首页 > 解决方案 > 如何在 GraphQL cURL POST 请求的 JSON 正文中插入 bash 变量

问题描述

我一直在花费数小时尝试格式化我的 json 帖子正文,以便我的脚本很开心,但我没有任何运气。在下面的代码中,我想使用 $utc_format 变量作为 datetime_gt 键的值。

#!/bin/bash

utc_format=$(date -v-3d -v-5M -u +"%Y-%m-%dT%H:%M:%SZ")

curl \
    -X POST \
    -H "Content-Type: application/json" \
    -H "X-Auth-Email: email@email.com" \
    -H "X-Auth-key: $API_KEY" \
    --data '{"query": "query { viewer { zones ( filter: { zoneTag_in: [ \"abcde12345\" ] } ) { firewallEventsAdaptive ( filter: { source: \"waf\" datetime_gt: \"$utc_format\" ruleId: \"123456\" action: \"simulate\" } orderBy: [ datetime_DESC ] limit: 100 ) { clientIP edgeResponseStatus metadata { key value } } } } }"}' \
    https://api.api.com/ \
    | python -m json.tool >> curl_results

我什至尝试做类似的事情:

generate_post_data()
{
cat <<EOF
{
<json data>
}
EOF
}

但我有一个错误说

"message": "failed to recognize JSON request: 'invalid character '\\n' in string literal'"

:'(

先感谢您!

标签: jsonbashcurlpostgraphql

解决方案


该消息的字面意思是您的 json 正文中有换行符。尝试删除换行符,看看是否有帮助。

curl \
    -X POST \
    -H "Content-Type: application/json" \
    -H "X-Auth-Email: email@email.com" \
    -H "X-Auth-key: $API_KEY" \
    --data "$(generate_post_data | tr -d '\n')" \
    https://api.api.com/ \
    | python -m json.tool >> curl_results

推荐阅读