jq过滤内部数组元素,但返回整个JSON

时间:2020-07-10 18:02:47

标签: json filter jq

TL; DR

在过滤顶级键的内部数组元素之后,如何返回整个JSON?

详细说明

我有一个描述COCO图像数据库的JSON,其格式如下(不相关的元素被截断为import random class Ball: def __init__(self, radius): self.radius = radius def radius(): return random.randint(1, 10) ball = Ball(radius()) ball = Ball(radius()) class Bag: def __init__(self, slots): self.slots = slots bag = Bag([1, 2]) bag.slots[0] = ball bag.slots[1] = ball print(bag.slots[0].radius) print(bag.slots[1].radius) )。

...

我需要过滤{ "info": { "description": "COCO 2017 Dataset", ... }, "licenses": [ { "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/", ... }, ... ], "images": [ { "license": 4, ... }, "annotations": [ { "segmentation": [ [ 510.66, ... ] ], "area": 702.1057499999998, "iscrowd": 0, "image_id": 289343, "bbox": [ 473.07, 395.93, 38.65, 28.67 ], "category_id": 18, "id": 1768 }, "categories": [ { "supercategory": "person", ... }, ] } ,其中annotations具有多个值之一,例如category_id

我可以成功地用{p>过滤这样的1, 2

category_id

但是,返回的仅是总JSON的注释元素,如下所示。

jq -C ' .annotations[] | select( .category_id == 1 or .category_id == 2 ) ' instances_val2017.json | less -R

我知道可以通过将表达式包装在{ "segmentation": [ [ 162.72, ... ] ], "area": 426.9120499999995, "iscrowd": 0, "image_id": 45596, "bbox": [ 161.52, 507.18, 46.45, 19.16 ], "category_id": 2, "id": 124742 } { ... { 中来将这些元素作为数组返回,但是在过滤指定的类别ID之后如何返回整个原始JSON?

1 个答案:

答案 0 :(得分:1)

好吧,昨天我花了3个小时试图解决这个问题,然后今天早上我发布了这个问题,并随后解决了这个问题!

这是使用|=运算符的解决方案,该运算符可在适当位置修改元素。

jq '.annotations |= map(select(.category_id | contains(1,2)))' instances_val2017.json

根据@peak的建议,这是使用==而不是contains的命令。

jq '.annotations |= map(select(.category_id == (1,2)))' instances_val2017.json
相关问题