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

时间:2018-02-14 17:10:13

标签: json key jq missing-data

我有以下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": []
                }
            }
        }
    ]
}
}

您希望获得ID和主猫ID,以便我这样做

cat test2.json | jq -c '.hits.hits[]|{products_ids: ._id, cat_id: ._source.category.master_category.id}'

但不幸的是我收到了一个错误: jq:error(at:48):无法使用字符串" id"

索引数组

那是因为对于第二次点击,没有.source.category.master_category.id

我尝试使用if then else和.source.category.master_category.id> 0进行测试,但仍然存在错误。所以我需要测试.source.category.master_category.id,但我找不到如何做到这一点。感谢

1 个答案:

答案 0 :(得分:1)

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

.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检查属性是否存在。