检查 linux 中 curl 响应的 json 字段

Check json field from the curl response in linux

我正在 gitlab-ci 文件中编写脚本,我使用的服务器是 Linux 到 运行 管道。

现在我想进行两次 API 调用,第二次调用依赖于第一次

例如

URL= you can take any HTTPS endpoint (i guess it really doesn't matter)

jsonResponse=$(curl -d $requestJson -X POST $FIRST_URL)

echo $jsonResponse

[{"result":"Success"}]

根据结果字段 (success/failure),我想使用 curl 进行另一个 API 调用。类似下面

if response[0].result=success then "curl -d $requestJson -X POST $SECOND_URL" else exit 1

请注意,响应将在数组中。

I want to make two rest API call and 2nd rest call is dependent on the 1st response

请根据协议推理:所以HTTPS (or HTTP) and REST。阅读更多关于它们的信息。

您可以使用一些现有的 JSON library (e.g. jansson in C, or jsoncpp in C++) and combine them with some HTTP client library (e.g. libcurl) and/or HTTP server library (e.g. libonion)。

您可能对现有的 C++ 框架感兴趣,例如 Qt or POCO

你应该看看最近的语言实现,比如Go or Rust or Ocaml or SBCL or Node.JS。他们提供有用的库(与 HTTP 和 REST 相关,包括客户端和服务器端)。

您可以考虑使用脚本语言,例如Python or Guile or Lua or Perl or Ruby等.....他们也有满足您需要的相关库。

阅读您要使用的编程语言实现和库的文档。

我倾向于认为 GNU bash is not the best alternative for your needs (consider also at least GNU gawk).

也看看github and gitlab for open source implementations relevant to your needs. Once these are specified (perhaps using EBNF notation for the messages you want to implement; read also about SOAP and JSONRPC) 在纸上,实现起来相当容易。

务必阅读Advanced Linux Programming and syscalls(2) and sockets(7)

What will correct way to validate the field

首先,在纸上指定哪些是有效字段。

另外,写几个有效字段和无效字段的例子。然后考虑使用regex(7)。也学习寻找灵感现有开源软件的源代码与您的需求.

另见 this

你可能做的是将第一次 API 调用的输出保存到一个文件 (api1-output.json),然后将它传递给下一个你可以读取该输出并根据其响应采取行动。

您的 .gitlab-ci.yml 文件中的示例:

api1_execution:
   image: your_image
   script:
      - curl -XGET https://my-api1-endpoint.com/api/getSomething > scripts/api1-output.json
   artifacts:
      paths:
         - scripts/api1-output.json


api2_execution:
   image: your_image
   script:
      - API1_OUTPUT= $(cat scripts/api1-output.json)
      - // do whatherever you want with API1_OUTPUT
      - // fire 2nd API call

为了解析和读取 JSON 输出,我强烈建议您使用名为 jQ

的工具

从我的角度来看,上面的示例可以作为您如何完成的想法。