You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决响应末尾带数字时jq报‘Cannot index number with string’错误

问题原因及解决办法

问题根源

你的curl命令使用了-w "%{http_code}\n"参数,这个参数会把HTTP状态码(200)追加到服务器返回的JSON响应末尾,导致response变量里的内容是完整JSON数据 + 换行 + 200。当jq处理该输入时,会把最后的200解析成一个单独的JSON数字值。执行._links操作时,jq先处理前面的JSON对象没问题,但接着会尝试对数字200执行._links索引——数字类型不支持字符串索引,因此触发Cannot index number with string "_links"报错。

解决方案

有两种常用处理方式:

1. 分离响应体与状态码

用curl的-o参数将响应体保存到临时文件,同时用-w把状态码存入单独变量:

#!/bin/bash
set -e

keyword="config"
temp_file=$(mktemp)

# 保存响应体到临时文件,状态码存入http_code变量
http_code=$(curl --location "${HEADERS[@]}" -s -o "$temp_file" -w "%{http_code}" -X GET "$url")

if grep "$keyword" "$temp_file"; then
    extract=$(jq -r "._links" "$temp_file")
    echo "$extract"
fi

rm "$temp_file" # 清理临时文件

2. 从response变量剥离状态码

如果不想使用临时文件,可通过字符串处理移除最后一行的状态码:

#!/bin/bash
set -e

keyword="config"

response=$(curl --location "${HEADERS[@]}" -s -w "%{http_code}\n" -X GET "$url")
# 提取除最后一行外的所有内容作为JSON
json_response=$(echo "$response" | sed '$d')

if echo "$json_response" | grep "$keyword"; then
    extract=$(jq -r "._links" <<< "$json_response")
    echo "$extract"
fi

内容的提问来源于stack exchange,提问作者Preeti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:45:11