jqを使用して子ノードセレクタを介して親ノードを取得する

jqを使用して子ノードセレクタを介して親ノードを取得する

jqでjsonを解析しようとしています。

{
    "xxx": {
        "aliases": {
            "business_event": {
                "is_write_index": true
            }
        },
        "mappings": {
            "business_event_doc": {
                "properties": {
                    "clientName": {
                        "type": "keyword"
                    },
                    "componentName": {
                        "type": "keyword"
                    },
                    "correlationId": {
                        "type": "keyword"
                    },
                    "executionTime": {
                        "type": "long"
                    },
                    "fullDescription": {
                        "type": "text"
                    },
                    "shortDescription": {
                        "type": "text"
                    }
                }
            }
        }
    }
}

結果が次のようにtype == "text"のプロパティリストを設定する必要があります。

"fullDescription": {
    "type": "text"
},
"shortDescription": {
    "type": "text"
}

セレクタを試してみましたが、結果が無効です。

.xxx.mappings[].properties | select (.[].type=="text")

子ノードを照会して親ノードを返す正しい方法は何ですか?

ベストアンサー1

問題

.xxx.mappings[].properties | select(.[].type=="text")

はい、selectオブジェクト全体(配列ではない)は、properties子オブジェクトが含まれている回数だけ選択されます.type == "text"

ここで使用できますwith_entries

jq '.xxx.mappings[].properties | with_entries(select(.value.type == "text"))' file

これはwith_entries属性を繰り返す。select次の要素の配列を取得します。

{
  "key": "clientName",
  "value": {
    "type": "keyword"
  }
}

select要素を選択.value.type == "text"して、通常のオブジェクトに置き換えます。

出力は次のとおりです

{
  "fullDescription": {
    "type": "text"
  },
  "shortDescription": {
    "type": "text"
  }
}

JSONドキュメントには「プライマリ」キー(キーはオブジェクトの一部ではない)を含めることができないため、要求された出力の正確な形式は有効なJSONではありません。

おすすめ記事