【发布时间】:2018-12-22 10:36:59
【问题描述】:
之前没有使用过jq,但我想构建一个shell 脚本,它会获得JSON 响应并仅提取值。为了学习,我想我会尝试使用我博客的 WP API,但由于某种原因,我收到了以下错误:
jq: 错误 (at :322): 不能用字符串“slug”索引数组
在研究和测试之前的问题时:
- jq: Cannot index array with string
- jq is sed for JSON
- JSON array to bash variables using jq
- How to use
jqin a shell pipeline? - How to extract data from a JSON file
我尝试编码的上述阅读:
URL="http://foobar.com"
RESPONSE=$(curl -so /dev/null -w "%{http_code}" $URL)
WPAPI="/wp-json/wp/v2"
IDENTIFIER="categories"
if (("$RESPONSE" == 200)); then
curl -s {$URL$WPAPI"/"$IDENTIFIER"/"} | jq '.' >> $IDENTIFIER.json
result=$(jq .slug $IDENTIFIER.json)
echo $result
else
echo "Not returned status 200";
fi
在curl 之后更改jq 的额外尝试:
curl -s {$URL$WPAPI"/"$IDENTIFIER"/"} | jq '.' | $IDENTIFIER.json
result=(jq -r '.slug' $IDENTIFIER.json)
echo $result
我可以用python JSON工具修改解压:
result=(curl -s {$URL$WPAPI"/"$IDENTIFIER"/"} | python -m json.tool > $IDENTIFIER.json)
我可以将 JSON 保存到一个文件中,但是当我使用 jq 时,我不能只得到 slug,这是我的其他尝试:
catCalled=$(curl -s {$URL$WPAPI"/"$IDENTIFIER"/"} | python -m json.tool | ./jq -r '.slug')
echo $catCalled
我的最终目标是尝试在 shell 脚本中使用 jq 并使用 jq 构建一个 slug 数组。我在jq 中做错了什么,我可以在不创建文件的情况下在字符串上使用jq 吗?
根据评论请求解压缩后从curl返回:
[
{
"id": 4,
"count": 18,
"description": "",
"link": "http://foobar.com/category/foo/",
"name": "Foo",
"slug": "foo",
"taxonomy": "category",
},
{
"id": 8,
"count": 9,
"description": "",
"link": "http://foobar.com/category/bar/",
"name": "Bar",
"slug": "bar",
"taxonomy": "category",
},
{
"id": 5,
"count": 1,
"description": "",
"link": "http://foobar.com/category/mon/",
"name": "Mon",
"slug": "mon",
"taxonomy": "category",
},
{
"id": 11,
"count": 8,
"description": "",
"link": "http://foobar.com/category/fort/",
"name": "Fort",
"slug": "fort",
"taxonomy": "category",
}
]
最终我的目标是尝试将蛞蝓的名称放入一个数组中,例如:
catArray=('foo','bar','mon', 'fort')
【问题讨论】:
-
你能发布服务器响应吗?
-
@hnicke 添加了 JSON 示例。