linux - 如何从curl响应中获取某些JSON值

标签 linux shell curl command-line-interface

我正在尝试执行以下请求负载(JSON)并获取响应,如下所示:

CURL 命令:

curl --header "Content-Type: application/json" --header "hostname:kindle.qa.amazon.com" \
--request POST \
--data '{
"country":"BE",
"cardNumberPayment":"9423-8234-1882-3412",
"cardType" : "Visa",
"expirationMonth": "12",
"expirationYear": "2020"
}' \
  http://amazon.qa.payment.com/v1/Services/restservices/credit

回应:

{"cardType":"Visa","cardNumber":"9423823418823409","cvv":"***"}
{"cardType":"Visa","cardNumber":"9423823418823411","cvv":"***"}
{"cardType":"Visa","cardNumber":"9423823418823410","cvv":"***"}

我只想获取curl命令的cardNumber,而不是打印整个JSON(除了cardType和cvv)。

预期输出:

9423823418823409
9423823418823411
9423823418823410

我只想单独获取卡号列表作为输出进行打印。我怎样才能实现这个目标?

最佳答案

您必须使用 JSON 解析器来提取信息。您可以使用 jq 来做到这一点(jq 是一个轻量级的命令行 JSON 处理器。)

这个article更详细地描述了如何实现这一目标。他们还有一个 tutorial here .

例如

curl 'http://amazon.qa.payment.com/v1/Services/restservices/credit' | jq '.[0]'

将提取数组的第一个元素(假设它是一个数组 - 您的代码使其看起来像一系列对象)。

然后按照以下方式获取卡号:

jq '.[0] | .cardNumber'

SO post too 中还有其他几个示例.

关于linux - 如何从curl响应中获取某些JSON值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57194454/

相关文章:

linux - .htaccess RewriteRule 将 http 重定向到 https 搞乱了 URL 中的 % 转义参数

c - C shell 中的输出重定向

linux - 每 15 分钟运行一次 crontab 不适用于 linux redhat

bash - zsh 中的 checkwinsize 等效项?

curl - 如何在 Chef 配方中执行 curl 命令?

http - 为什么 HTTP 响应头中的 "Connection"拼写错误?

linux - 传递答案时出现无限循环问题

c - 从Linux内核解释notifier.c

linux - make <package> 意味着新的提取

PHP curl 将 Content-Type 更改为 application/x-www-form-urlencoded。不应该那样做