I'm studying about shell script and I got stuck into a problem.
I have to monitor a API URL that returns to me a response in JSON format. Here's a example of this response:
{
"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",
}
}
}
]
}
The problem is that I need that the curl command returns to me three params: 1. the "name" (which is in the json response), 2. the http code and 3. the time response. For example, I expect something like this:
santa-claus #from json extract
200 #http code
347ms #time response
I'm using shell script, and what I have now is this curl command:
curl -X "GET" -w "%{http_code}\n" "https://my-api-url-here&compress=true" | jq -r '.Items[] | .descs.por.name'`
This is returning to me this error:
curl: (3) <url> malformed
jq: error (at <stdin>:1): Cannot index number with string "Items"
santa-claus
The "jq" part is correct, if I do this curl without "-w "%{http_code}\n"", everything is ok. But I need that three responses, as I said... about time response, I read something about "%{time_starttransfer}", but I don't know how to apply this in my curl command...
Is that a way to do this?
You can have curl
output a custom JSON object which jq
can then parse as well. (The values http_code
and time_total
take should be safe for this kind of interpolation.)
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'
The block output by -w
will follow the body of the request as a separate object. The -s
option reads both objects into a single array, which your filter than then index as necessary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.