我正在尝试使用应用程序的API文档。
为了调用它,我使用了以下代码:
curl -X GET \
'https://api.program.com/v1/notes?page=1&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer xxx123xxx456xxx789xxx0001' \
-H 'cache-control: no-cache'由于明显的原因,这里对令牌进行了更改。但是,我真正想要设置的是page=1参数。
我的问题有两方面:
page=1之后,它会运行page=2,page=3,.我目前的设置看起来是这样的,但是它给了我我需要的东西(我不太清楚这一点),而且我也不知道如何打破循环:
for ((i=1;i<=5;i++)); do
curl -X GET \
'https://api.program.com/v1/notes?page=1&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer xxx123xxx456xxx789xxx0001' \
-H 'cache-control: no-cache'
done当没有更多的记录时,结果如下:
{
"meta": {
"pageSize": 1000,
"page": 65
},
"links": {
"self": "/v1/conversations?page=65&pageSize=1000&sort=desc",
"first": "/v1/conversations?page=1&pageSize=1000&sort=desc",
"prev": "/v1/conversations?page=64&pageSize=1000&sort=desc",
"next": null
},
"data": []
}根据查尔斯·达菲的回应--被保存为test_run.sh
getPage () {
curl -X GET 'https://api.test.com/v1/test?page="$1"&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9Cim97g123NXpMkS_Jc9xggCYlMQVvKsAeBCw' \
-H 'cache-control: no-cache'
}但这会返回错误:
MacBook-Pro-8:~ admin$ ./test_run.sh
-bash: ./json_blob.sh: Permission denied但是,当我在命令行中直接运行以下命令时,它将返回结果:
curl -X GET 'https://api.test.com/v1/test?page="$1"&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9Cim97g123NXpMkS_Jc9xggCYlMQVvKsAeBCw' \
-H 'cache-control: no-cache' > test_run.json发布于 2019-02-20 12:37:41
对于每次迭代,您需要检查是否存在"next" : null,如果找到,则中断循环。
while : ; do
if [[ $(curl -X GET 'https://api.program.com/v1/notes?page=1&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer xxx123xxx456xxx789xxx0001' \
-H 'cache-control: no-cache' | jq '.link.next') == 'null' ]] ; then
break #Exit the loop
fi
done发布于 2019-02-20 14:47:24
在实践中,我可能会编写更类似于以下内容的内容:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[12].*) echo "Bash 3.0+ required" >&2; exit 1;; esac
# Given a page number, return text of that page.
# Note that we switch from single to double quotes before expanding $1
getPage() {
curl --fail -X GET 'https://api.program.com/v1/notes?page='"$1"'&pageSize=1000&sort=desc' \
-H 'Authorization: Bearer xxx123xxx456xxx789xxx0001' \
-H 'cache-control: no-cache'
}
# return a stream with *all* page text, from page 1 until
# the first one with no .link.next.
getAllPages() {
local page i=1
while page=$(getPage "$i"); do
printf '%s\n' "$page"
if [[ $(jq '.links.next' <<<"$page") = null ]]; then
break
fi
(( ++i ))
done
}
getAllPages \
| jq -c '.data[] | .attributes | {text: .preview, from: .meta.from}' \
> data_json_blob.jsonl这里的输出文件名为.jsonl,因为它是JSONLines格式的,而不是标准的JSON。(如果不将多个对象封装在一个列表或其他容器中,并且它是有效的,就不能将多个对象放入一个JSON文件中;因此,当您在输入上输入一个以上的jq转换时,通常会得到JSONL,而不是JSON作为输出)。
https://stackoverflow.com/questions/54778695
复制相似问题