如何在 POST cURL 请求 JSON 数据中插入另一个 JSON?

How to insert another JSON, in the POST cURL request JSON data?

我的 report json 看起来像这样:

{
  "passed": 11,
  "total": 11,
  "collected": 11
}

我定义了一个变量test_report并给它赋了上面的值。但无法在 curl 命令中使用它?我看到错误 invalid_payload gcloud build logs

- name: gcr.io/cloud-builders/gcloud:latest
  entrypoint: 'bash'
  dir: 'workspace'
  env:
  - 'TEST_REPORT=${_TEST_REPORT}'
  args:
  - '-c'
  - |
    cd /workspace
#Installing jq
    apt-get update -y && apt-get install -y curl unzip groff jq bc less
#testing jq is successfully installed or not
    jq --help
    cat mezi_automation_test_report.json
#assgined summary object to test_report file
    jq .summary mezi_automation_test_report.json > test_report
#check test_report file is displayed with summary object or not
    cat test_report
    report=$(cat test_report)
#check report variable has summary object or not
    echo report

    curl --location --request POST '$_SLACK_WEBHOOK' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "channel":"$_CHANNEL",
        "username":"Cloudbuild",
        "icon_url":"$_ICON_URL",
        "text":"Test Report",
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": " Test Report *`$_BRANCH`* branch on QA"
                }
            },
            {
                "type": "divider"
            },
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                  "text": "Version: *$_VERSION*\n TEST_REPORT: *"${report}"*"
                }
            }
        ]
    }'

' 单引号内的任何内容都不能被解释或读取为正则表达式,因此您必须先关闭它,然后再使用任何 bash command/variable。之后,您可以再次开始单引号以附加 string/json.

的剩余部分

注意:如果 bash 命令有一个像 json 值这样的特殊输出,请用双引号将其括起来 "

test_report=$(jq .summary mezi_automation_test_report.json)
curl "http://localhost/send" -d '{"text":'"$test_report"' } '

或者如果您想要更多控制,请分别解析每个数据值

passed=$(jq .summary.passed mezi_automation_test_report.json)
total=$(jq .summary.total mezi_automation_test_report.json)
collected=$(jq .summary.collected mezi_automation_test_report.json)
curl "http://localhost/send" -d '{"text":"Test Report: \nPassed: '$passed' \nTotal: '$total' \nCollected: '$collected' \nEnd of Report" } '