如何在构建对象时避免生成所选数据的所有组合?

问题描述

下面给出了我的原始JSON。

[
  {
    "id": "1","name": "AA_1","total": "100002","files": [
      {
        "filename": "8665b987ab48511eda9e458046fbc42e.csv","filename_original": "some.csv","status": "3","time": "2020-08-24 23:25:49"
      }
    ],"created": "2020-08-24 23:25:49","filenames": "8665b987ab48511eda9e458046fbc42e.csv","is_append": "0","is_deleted": "0","comment": null
  },{
    "id": "4","name": "AA_2","total": "43806503","files": [
      {
        "filename": "1b4812fe634938928953dd40db1f70b2.csv","filename_original": "other.csv","total": "21903252","time": "2020-08-24 23:33:43"
      },{
        "filename": "63ab85fef2412ce80ae8bd018497d8bf.csv","status": "2","total": 0,"time": "2020-08-24 23:29:30"
      }
    ],"created": "2020-08-24 23:35:51","filenames": "1b4812fe634938928953dd40db1f70b2.csv&&63ab85fef2412ce80ae8bd018497d8bf.csv","comment": null
  }
]

我要从此JSON通过合并状态为 2 的对象和它们的文件也具有相同对 status的对象的字段来创建新对象:2

因此,我期望如下所示的JSON数组。

[
  {
    "id": "4","file_filename": "63ab85fef2412ce80ae8bd018497d8bf.csv","file_status": 2
  }
]

到目前为止,我尝试使用此JQ过滤器:

.[]|select(.status=="2")|[{id:.id,file_filename:.files[].filename,file_status:.files[].status}]

但这会产生一些无效的数据。

[
  {
    "id": "4",# want to remove this as file.status != 2
    "file_filename": "1b4812fe634938928953dd40db1f70b2.csv","file_status": "3"
  },"file_filename": "1b4812fe634938928953dd40db1f70b2.csv","file_status": "2"
  },# Repeat
    "file_filename": "63ab85fef2412ce80ae8bd018497d8bf.csv","file_status": "2"
  }
]

如何使用JQ过滤新的JSON并删除这些重复的对象?

解决方法

通过两次将 [] 运算符应用于文件,您正在遇到组合爆炸。需要避免这种情况,例如:

[ .[] | select(.status == "2") | {id,name} + (.files[] | select(.status == "2") | {file_filename: .filename,file_status: .status}) ]

Online demo