gpt4 book ai didi

json - 使用 JQ 处理嵌套对象映射中的空值

转载 作者:行者123 更新时间:2023-12-04 08:16:09 24 4
gpt4 key购买 nike

我只是在学习 jq,在这里有点难住。假设我有一个名为 testcite.json 的文件像这样:

[
{
"id": "JoeSchmoe2020",
"abstract": "Here's some junk",
"author": [
{
"family": "Scmoe",
"given": "Joe"
},
{
"family": "Smith",
"given": "Sally"
}
],
"title": "I wrote words!"
},
{
"id": "EdithJones2020",
"abstract": "It's an abstract",
"author": [
{
"family": "Jones",
"given": "Edith"
},
{
"family": "Wilson",
"given": "Eric"
}
],
"title": "These are more words!"
}
]
并假设我想将其转换为如下内容:
[
{
"author": [
"Scmoe",
"Smith"
],
"title": "I wrote words!"
},
{
"author": [
"Jones",
"Wilson"
],
"title": "These are more words!"
}
]
以下命令可以让我得到我想要的东西......只要没有任何空值。
cat testcite.json | jq '[.[] | {author: .author | map(.family), title}]'
但是一旦出现空值,就会爆炸。假设我更改了 JSON:
[
{
"id": "JoeSchmoe2020",
"abstract": "Here's some junk",
"author": [
{
"family": "Scmoe",
"given": "Joe"
},
{
"family": "Smith",
"given": "Sally"
}
],
"title": "I wrote words!"
},
{
"id": "EdithJones2020",
"abstract": "It's an abstract",
"author": null,
"title": "These are more words!"
}
]
然后当我运行相同的命令时,我期望得到的将是
[
{
"author": [
"Scmoe",
"Smith"
],
"title": "I wrote words!"
},
{
"author": [],
"title": "These are more words!"
}
]
(我也很高兴用 null 代替空列表)。
不幸的是,相反,我收到了错误: jq: error (at <stdin>:23): Cannot iterate over null (null)我试过在问号中分散: cat testcite.json | jq '[.[] | {author: .author | map(.family?), title}]'只会产生相同的错误。 cat testcite.json | jq '[.[] | {author: .author | map(.family)?, title}]'产生语法错误:
jq: error: syntax error, unexpected '?', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
[.[] | {author: .author | map(.family)?, title}]
jq: 1 compile error
有什么办法可以让值提取来合理地处理空值?

最佳答案

一个直接的解决方案是测试 null ,例如

[.[]
| {author, title}
| .author |= if . then map(.family) else [] end
]
或类似:
map({author: (.author 
| if type == "array"
then map(.family)
else [] end),
title} )

关于json - 使用 JQ 处理嵌套对象映射中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65694712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com