如何在json字符串中插入bash变量



我有一个bash脚本,它向GraphQL端点发出post请求。帖子正文为JSON。基本上,在JSON中,我想用bash变量的值替换一个键/值对的值。我尝试过不同的组合,但都出现了错误。这是我的代码:

#!/bin/bash
utc_format=$(date -v-2d -v-23H -u +"%Y-%m-%dT%H:%M:%SZ")
curl -v 
-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: "100000" action: "simulate" } orderBy: [ datetime_DESC ] limit: 100 ) { clientIP edgeResponseStatus metadata { key value } } } } }"}' 
https://api.api.com/graphql 
| python -m json.tool >> curl_results

如果你看看我的代码在datetime_gt结束时,关闭--data中的"{"。然后在rule_id之前,我用"再次打开它。我做错了什么??我可能检查了一百次。每次尝试不同的格式时,都会弹出一个新的错误。目前(代码粘贴在这里(,我得到的错误是:

{
"data": null,
"errors": [
{
"extensions": {
"timestamp": "2020-12-21T03:32:11.090255834Z"
},
"message": "failed to recognize JSON request: 'invalid character '"' after object key:value pair'",
"path": null
}
]
}

检查它是否工作。至少你会有一个有效的JSON作为输出。

#!/bin/bash
utc_format=$(date -v-2d -v-23H -u +"%Y-%m-%dT%H:%M:%SZ")
curl -v 
-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: "100000" action: "simulate" } orderBy: [ datetime_DESC ] limit: 100 ) { clientIP edgeResponseStatus metadata { key value } } } } }"}' 
https://api.api.com/graphql 
| python -m json.tool >> curl_results

最新更新