使用 jq 中的 to_entries 跳过或忽略不存在的键

发布于 2025-01-12 06:27:15 字数 1011 浏览 0 评论 0原文

我正在尝试创建一个从每个 *.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏佲洛 2025-01-19 06:27:15

许多可能性之一是使用 try

.name as $n | .hobby | try to_entries[] | [ $n, .value]

try EXP 相当于 try EXP catch empty

One of many possibilities would be to use try:

.name as $n | .hobby | try to_entries[] | [ $n, .value]

try EXP is equivalent to try EXP catch empty.

一袭水袖舞倾城 2025-01-19 06:27:15

输入以下内容:

{
  "name": "bob",
  "hobby": [
    "baseball",
    "baseketball"
  ]
}

$ cat file | jq -c "{name,hobby:.hobby[]}|[.[]]"

["bob","baseball"]
["bob","baseketball"]

Enter the following:

{
  "name": "bob",
  "hobby": [
    "baseball",
    "baseketball"
  ]
}

$ cat file | jq -c "{name,hobby:.hobby[]}|[.[]]"

["bob","baseball"]
["bob","baseketball"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文