Text-Processing
在深度嵌套的 JSON 中為特定鍵名選擇特定的所有鍵路徑和值
我有一個非常大的半結構化 JSON 模式,嵌套單元結構由一個鍵標記:“ObjectType”以指示一些有意義的資訊。
我正在嘗試使用 jq 來選擇所有這些 ObjectType(s) 及其值的路徑。
json的範例部分是:
{ "ObjectType": "ClassZ", "LastModifiedBy": "janeroe", "Name": "Anonymous", "ArrayProps": [], "Logistics": [ { "ObjectType": "ClassA", "Source": "Vendor", "UUID": "x868-dhibye9-7678-12", "EffectiveDate": "2020-01-01", "Active": true, "Preferred": 0 } ], "IsVirtual": true, "Convention": 3, "CruiseParams": [ { "ObjectType": "ClassB", "Destinaton": "Atlantis", "Value": "3" } ], "InvolvedParties": [], "PartyEvents": [ { "ObjectType": "ClassC", "CreatedDate": "2020-01-01", "CreatedBy": "johndoe" } ], "FunFactors": [ { "ObjectType": "ClassD", "Level": 1 } ] }
試圖輸出類似或接近的東西:
"ObjectType": "ClassZ" "Logistics/0/ObjectType": "ClassA" "CruiseParams/0/ObjectType": "ClassB" "PartyEvents/0/ObjectType": "ClassC" "FunFactors/0/ObjectType": "ClassD"
這是我能想到的最好的方法,基於如何使用 jq 獲取找到的值的索引路徑?
$ jq -rc 'paths as $p | select($p[-1] == "ObjectType") | "\($p|@csv): \"\(getpath($p))\""' sample.json "ObjectType": "ClassZ" "Logistics",0,"ObjectType": "ClassA" "CruiseParams",0,"ObjectType": "ClassB" "PartyEvents",0,"ObjectType": "ClassC" "FunFactors",0,"ObjectType": "ClassD"
引用和定界並不完全符合您的要求 - 使用您
map(tostring)| join(“/“)
從評論中提出的建議,它變成$ jq -rc 'paths as $p | select($p[-1] == "ObjectType") | "\"\($p|map(tostring)|join("/"))\": \"\(getpath($p))\""' sample.json "ObjectType": "ClassZ" "Logistics/0/ObjectType": "ClassA" "CruiseParams/0/ObjectType": "ClassB" "PartyEvents/0/ObjectType": "ClassC" "FunFactors/0/ObjectType": "ClassD"