使用 jq 中的 to_entries 跳过或忽略不存在的键
我正在尝试创建一个从每个 *.json
文件转换而来的大型 CSV 文件。此代码片段一直有效,直到遇到没有密钥的文件 (hobby
)。
原始
{
"name": "bob",
"hobby": [
"baseball",
"baseketball"
]
}
jq 片段
cat *.json | jq '.name as $n | .hobby | to_entries[] | [ $n, .value]'
有效
[][]...
是使用 jq 创建 CSV 时的预格式
[
"bob",
"baseball"
]
[
"bob",
"baseketball"
]
https://jqplay.org/s/L-SmqiN-jw
然而如果.hobby
键不存在,它会严重失败。
jq: error (at <stdin>:6): null (null) has no keys
exit status 5
https://jqplay.org/s/gapUv1Tpmb
我尝试使用 if 块,但似乎不正确。我们怎样才能做到这样的事情或者
- return
[]
(空数组) - 跳过当前工作文件的 jq 执行并转到下一个
I'm trying to create a massive CSV file converted from each *.json
file. This snippet works until it faces the file that doesn't have the key (hobby
).
Original
{
"name": "bob",
"hobby": [
"baseball",
"baseketball"
]
}
jq snippet
cat *.json | jq '.name as $n | .hobby | to_entries[] | [ $n, .value]'
It works
[][]...
is a pre-format when creating CSV with jq
[
"bob",
"baseball"
]
[
"bob",
"baseketball"
]
https://jqplay.org/s/L-SmqiN-jw
However if the .hobby
key doesn't exist it fails miserably.
jq: error (at <stdin>:6): null (null) has no keys
exit status 5
https://jqplay.org/s/gapUv1Tpmb
I tried to use if block but it seems not correct. How can we do such a thing either
- return
[]
(empty array) - skip jq excution for the current working file with this problem and go to the next
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
许多可能性之一是使用
try
:try EXP
相当于try EXP catch empty
。One of many possibilities would be to use
try
:try EXP
is equivalent totry EXP catch empty
.输入以下内容:
Enter the following: