问题描述
我正在解析嵌套的json,以从json响应中获取特定值. json响应如下:
{
"custom_classes": 2,
"images":
[
{
"classifiers":
[
{
"classes":
[
{
"class": "football",
"score": 0.867376
}
],
"classifier_id": "players_367677167",
"name": "players"
}
],
"image": "1496A400EDC351FD.jpg"
}
],
"images_processed": 1
}
从类images => classifiers => classes:"class"& 分数"是我要保存在csv文件中的值.我发现了如何将结果保存在csv文件中.但是我无法单独解析images
.我可以得到custom_classes
和image_processed
.
我正在使用jq-1.5
.
我尝试过的不同命令:
curl "Some address"| jq '.["images"]'
curl "Some address"| jq '.[.images]'
curl "Some address"| jq '.[.images["image"]]'
在大多数情况下,该错误是有关无法为数组images
编制索引的.
有任何提示吗?
我必须说,我对jq
并不十分擅长,因此所有这些数组迭代都可能以某种方式被简化,但这产生了您提到的值:
cat foo.json | jq ".[] | .images | .[] | .classifiers | .[] | .classes | .[] | .[]"
如果您也想要按键,只需省略最后一个.[]
.
修改正如@chepner在评论中指出的,确实可以将其简化为
cat foo.json | jq ".images[].classifiers[].classes[] | [.class, .score] | @csv "
I am parsing a nested json to get specific values from the json response. The json response is as follows:
{
"custom_classes": 2,
"images":
[
{
"classifiers":
[
{
"classes":
[
{
"class": "football",
"score": 0.867376
}
],
"classifier_id": "players_367677167",
"name": "players"
}
],
"image": "1496A400EDC351FD.jpg"
}
],
"images_processed": 1
}
From the class images=>classifiers=>classes:"class" & "score" are the values that I want to save in a csv file. I have found how to save the result in a csv file. But I am unable to parse the images
alone. I can get custom_classes
and image_processed
.
I am using jq-1.5
.
The different commands I have tried :
curl "Some address"| jq '.["images"]'
curl "Some address"| jq '.[.images]'
curl "Some address"| jq '.[.images["image"]]'
Most of the times the error is about not being able to index the array images
.
Any hints?
I must say, I'm not terribly good at jq
, so probably all those array iterations could be shorthanded somehow, but this yields the values you mentioned:
cat foo.json | jq ".[] | .images | .[] | .classifiers | .[] | .classes | .[] | .[]"
If you want the keys, too, just omit that last .[]
.`
EditAs @chepner pointed out in the comments, this can indeed be shortened to
cat foo.json | jq ".images[].classifiers[].classes[] | [.class, .score] | @csv "
这篇关于用jq解析嵌套的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!