Json 如何检查jq中是否存在对象

Json 如何检查jq中是否存在对象,json,key,jq,missing-data,Json,Key,Jq,Missing Data,我有下面的Json { "_shards": { "failed": 0 }, "hits": { "hits": [ { "_id": "P16296", "_source": { "category": { "all_categories": [ {

我有下面的Json

{
"_shards": {
    "failed": 0
}, 
"hits": {
    "hits": [
        {
            "_id": "P16296", 
            "_source": {
                "category": {
                    "all_categories": [
                        {
                            "id": 76, 
                            "name": "Souris" 
                        }
                    ], 
                    "master_category": {
                        "id": 76, 
                        "name": "Souris" 
                    }
                }
            }
        }, 
        {
            "_id": "P749525", 
            "_source": {
                "category": {
                    "all_categories": [
                        {
                            "id": 1301, 
                            "name": "Produits abim\u00e9s", 
                        }
                    ], 
                    "master_category": []
                }
            }
        }
    ]
}
}
嗨,我想得到身份证和猫的主人身份证,所以我要这么做

cat test2.json | jq -c '.hits.hits[]|{products_ids: ._id, cat_id: ._source.category.master_category.id}'
但不幸的是,我得到了一个错误: jq:错误(at:48):无法为字符串为“id”的数组编制索引

这是因为第二次点击没有.source.category.master_category.id


我尝试使用if-then-else和.source.category.master\u category.id>0测试它,但仍然存在错误。所以我需要测试if.source.category.master_category.id,但我找不到如何做。谢谢

一种可能性是使用
后缀运算符,例如

.hits.hits[]
| { products_ids: ._id,
    cat_id: ._source.category.master_category.id? }
或者,如果您希望更具包容性:

.hits.hits[]
| { products_ids: ._id,
    cat_id: (._source.category.master_category.id? // null ) }

您还可以使用
has/1

检查属性是否存在。非常感谢,第二个对我最有帮助,因为我需要所有产品ID条目。第一个,不会吐出第二个产品。