我有一个非常大的半结构化 JSON 模式,嵌套的单元结构由键标记:“ObjectType”来指示一些有意义的信息。
我正在尝试使用 jq 来选择所有这些 ObjectType 及其值的路径。
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"
答案1
这是我能想到的最好的基于如何使用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"