寻求正确jq命令:从嵌套JSON提取关联字段数据
正确提取JSON关联字段的jq命令
你之前的命令生成所有字段组合,本质是没按层级关联遍历,不同层级的数组被单独展开,导致了笛卡尔积。
先给一个符合你描述的典型JSON结构示例,方便你对应自己的结构调整:
{ "vulnerabilities": [ { "productName": "Product A", "parentAlert": { "answers": [ { "willBeFixed": true, "fixedInPackage": "1.2.3" }, { "willBeFixed": false, "fixedInPackage": null } ] }, "affectedVersions": ["1.0.0", "1.1.0"] }, { "productName": "Product B", "parentAlert": { "answers": [ { "willBeFixed": true, "fixedInPackage": "2.0.1" } ] } } ] }
针对这个结构,正确的jq命令如下:
.vulnerabilities[] | .productName as $product | .parentAlert.answers[] | { productName: $product, willBeFixed: .willBeFixed, fixedInPackage: .fixedInPackage }
关键逻辑说明:
.vulnerabilities[]逐个遍历顶层的漏洞条目.productName as $product把当前漏洞条目的产品名存为变量$product,确保后续每个answers条目都能关联到所属产品.parentAlert.answers[]遍历当前漏洞条目下的所有answers项- 最后构造包含三个目标字段的对象,这样每个answers条目都会和对应的productName绑定,不会出现乱组合的情况
如果你的JSON结构里,answers的位置不在parentAlert下(比如在affectedVersions的子节点里),只需要调整遍历路径即可,核心就是先把上层的productName存为变量,再遍历下层的answers数组,保证关联关系。
内容的提问来源于stack exchange,提问作者fabbb
相关产品推荐
相关产品推荐

