当某些键仅存在于少数数组中时,不确定使用 jq 过滤一组 json 数组的最有效方法 - //?

not sure about the most efficient way to filter a set of json arrays with jq when some keys are only present in a few arrays - //?

刚开始使用 jq 尝试合并一些键,这些键位于从 curl 传输的更大 json 文件中。

curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename}'

curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename, phone: .contact[]? .number}'

curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename, phone: .contact[]? .number} // {name: .firstname, job: .position, location: .sites[]? .officename}'

谢谢

---编辑:在下面添加一个 test.json 的简短示例以实现再现性:

{
   "id": 1,
   "array": [{
         "firstname": "Nobody",
         "lastname": "Nothing",
         "sites": [{
            "officename": "Site1",
            "city": "City"
         }],
         "position": "Test1"
      },
      {
         "firstname": "Anybody",
         "lastname": "Anything",
         "sites": [{
            "officename": "Site2",
            "city": "City2"
         }],
         "position": "Test2",
         "contact": [{
            "number": "123-456-7890",
            "email": "test@test.com"
         }]
      }
   ]
}

也许您正在寻找以下解决方案的变体:

.array[]
| {name: .firstname, job: .position, location: .sites[]? .officename}
  +  ({phone: .contact[].number}? // null)

(重点是将 null 添加到 JSON 对象会产生相同的对象。)

这个变体当然带有与原始版本相同的警告。特别是,使用除第一个数组迭代器以外的所有迭代器可能会有问题。