我有一个文件,我们将其命名为heroes.json,其中的部分数据是对象superpowers的嵌套数组
[
{
"hero": "Superman",
"id": "123",
"realName": "Clark Kent",
"age": "?",
"superpowers": [
{
"name": "speed",
"num": "1",
"des": "Faster than a speeding bullet.",
"value": "50"
},
{
"name": "strength",
"num": "2",
"des": "More powerful than a locomotive.",
"value": "100"
}
],
"weakness": "kryptonite"
},
{
"hero": "Batman",
"id": "456",
...我想选择hero和superpowers,并且只在superpowers中保留name和des密钥,如下所示:
[
{
"hero": "Superman",
"superpowers": [
{
"name": "speed",
"des": "Faster than a speeding bullet."
},
{
"name": "strength",
"des": "More powerful than a locomotive."
}
]
},
{
"hero": "Batman",
"superpowers": [
...编写一个迭代器来做这件事并不难,但我想尝试一下jq,因为我是这个工具的新手,学习它似乎很有用。
发布于 2020-12-19 11:21:30
因此,我在jqplay上进行了试验,直到它提供了所需的格式。我不知道它是否是最优的,但这是可行的:
jq '[.[] | {hero, superpowers: [ .superpowers[] | {name, des} ] } ]'
(类似graphQL的筛选器语法将使这一点变得更容易。)
注意:我的json所需的输出与this question and answer中提到的不同,我已经避免在解决方案中使用map (迭代器)。换句话说,我不是在问同样的问题,也不是给出同样的答案。
如果知道我的解决方案是最优的,这将是很有帮助的。
https://stackoverflow.com/questions/65366371
复制相似问题