当某些键仅存在于少数数组中时,不确定使用 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 文件中。
- 以下命令按预期输出所有 10 条记录中的所需信息:
curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename}'
- 2 条记录有一个附加键,其他记录没有。将该键添加到命令会导致仅为这两条记录返回键。使用
jq: error: Cannot iterate over null
: 从 .contact[]?
错误中删除 ?
curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename, phone: .contact[]? .number}'
- 目前正在通过使用 // 运算符解决此问题,如下所示。以这种方式使用 jq 是否有更有效或更推荐的方法?
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 对象会产生相同的对象。)
这个变体当然带有与原始版本相同的警告。特别是,使用除第一个数组迭代器以外的所有迭代器可能会有问题。
刚开始使用 jq 尝试合并一些键,这些键位于从 curl 传输的更大 json 文件中。
- 以下命令按预期输出所有 10 条记录中的所需信息:
curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename}'
- 2 条记录有一个附加键,其他记录没有。将该键添加到命令会导致仅为这两条记录返回键。使用
jq: error: Cannot iterate over null
: 从
.contact[]?
错误中删除 ?
curl http://localhost/test.json | jq -r '.array[] | {name: .firstname, job: .position, location: .sites[]? .officename, phone: .contact[]? .number}'
- 目前正在通过使用 // 运算符解决此问题,如下所示。以这种方式使用 jq 是否有更有效或更推荐的方法?
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 对象会产生相同的对象。)
这个变体当然带有与原始版本相同的警告。特别是,使用除第一个数组迭代器以外的所有迭代器可能会有问题。