简体   繁体   English

如何使用 JQ 将 JSON 值列表添加到键中

[英]how to add a list of JSON values into keys with JQ

I have an input file:我有一个输入文件:

{
  "errands": [
    {
      "name": "broker-deregistrar",
      "label": "Deregister and Purge Instances",
      "impact_warning": null,
      "pre_delete": true
    },
    {
      "name": "delete-all-service-instances",
      "label": "Delete All Service Instances",
      "impact_warning": null,
      "pre_delete": true
    },
    {
      "name": "deregister-broker",
      "label": "Deregister On-Demand Service Broker",
      "impact_warning": null,
      "pre_delete": true
    }
  ]
}

I would like to reformat this to make the values of .name into a key with a fixed value like this:我想重新格式化它以使.name的值成为具有固定值的键,如下所示:

{
"deploy_products": "all",
"errands": {
    "product_1_guid": {
      "run_pre_delete": {
        "broker-deregistrar": true,
        "delete-all-service-instances": true,
        "deregister-broker": true
      }
    }
  },
  "ignore_warnings": true
}

I can subset the values I want with this filter:我可以使用这个过滤器对我想要的值进行子集化:

.errands[].name

which gives me:这给了我:

"broker-deregistrar"
"delete-all-service-instances"
"deregister-broker"

but I want to get the selected values into a new JSON as keys.但我想将选定的值作为键放入新的 JSON 中。

while this kind of works,虽然这种作品,

.errands=(.product_1_guid=(.run_pre_delete=(.xxx=true | .yyy=true | .zzz=true)))

the list of errand names is variable in that they have different names and counts.差事名称列表是可变的,因为它们具有不同的名称和计数。 ie the list of errands may only be "delete-apps", or even nothing at all.即,差事列表可能只是“删除应用程序”,甚至什么都没有。

and in the above example I need .xxx , .yyy and .zzz to come from the original JSON.在上面的示例中,我需要来自原始 JSON 的.xxx.yyy.zzz

Generate the name-true pairs within an array constructor so that you can easily merge them with add and place the result wherever it belongs.在数组构造函数中生成 name-true 对,以便您可以轻松地将它们与add合并并将结果放在它所属的任何位置。

{
  deploy_products: "all",
  errands: {
    product_1_guid: {
      run_pre_delete: [
        { (.errands[].name): true }
      ] | add
    }
  },
  ignore_warnings: true
}

Online demo在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM