【问题标题】:curl to return http code, time response and extract a json valuecurl 返回 http 代码、时间响应并提取 json 值
【发布时间】:2022-01-17 23:28:12
【问题描述】:

我正在研究 shell 脚本,但遇到了一个问题。

我必须监控一个以 JSON 格式返回给我响应的 API URL。以下是此响应的示例:

         {
                "Result": 0,
                "ExecutionTime": 0,
                "Items": [
                    {
                        "item1": "x",
                        "item2": x,
                        "item3": x,
                        "item4": x,
                        "genre1": x,
                        "genre2": x,
                        "item5": x,
                        "item6": x,
                        "desc": {
                            "por": {
                                "name": "santa-claus",
                                "item7": "xxxx",
        }
        }
}
        ]
    }

问题是我需要 curl 命令返回给我三个参数:1.“名称”(在 json 响应中),2.http 代码和 3.时间响应。例如,我希望是这样的:

santa-claus    #from json extract
200            #http code
347ms          #time response

我正在使用 shell 脚本,而我现在拥有的是这个 curl 命令:

curl -X "GET" -w "%{http_code}\n" "https://my-api-url-here&compress=true" | jq -r '.Items[] | .descs.por.name'`

这是返回给我这个错误:

curl: (3) <url> malformed
jq: error (at <stdin>:1): Cannot index number with string "Items"
santa-claus

“jq”部分是正确的,如果我在没有“-w”%{http_code}\n“”的情况下执行此 curl,则一切正常。但正如我所说,我需要这三个回应...... 关于时间响应,我读过一些关于“%{time_starttransfer}”的内容,但我不知道如何在我的 curl 命令中应用它...

这是一种方法吗?

【问题讨论】:

    标签: json shell curl sh jq


    【解决方案1】:

    您可以让curl 输出一个自定义 JSON 对象,jq 然后也可以解析该对象。 (值http_codetime_total take 对于这种插值应该是安全的。)

    curl -X "GET" -w '{"code": "%{http_code}", "time": "%{time_total}"}' "https://my-api-url-here&compress=true" |
      jq -sr '.[0].Items[] | .descs.por.name, .[1].code, .[1].time'
    

    -w 的块输出将作为单独的对象跟随请求的主体。 -s 选项将两个对象读取到一个数组中,然后您的过滤器会根据需要对其进行索引。

    【讨论】:

    • 谢谢你的回答!!我明白!试图在这里执行此操作,它几乎就在那里,但我现在得到了这个:“ santa-claus jq: error (at :1): Cannot index object with number jq: error (at :1): cannot带有数字的索引对象“代码”和“时间”响应中有问题,我已经看到在您制作的这种格式中,这两个选项就像在与 url json 响应相同的 json 中,在行尾
    • 可能需要'(.[0].Items[] | .descs.por.name), .[1].name, .[1].time',因为我认为| 的优先级低于,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2021-07-29
    • 2012-05-05
    • 2012-04-01
    相关资源
    最近更新 更多