jq:限制复杂 json 中的所有数组

发布于 2025-01-11 06:37:11 字数 312 浏览 0 评论 0原文

尝试以下代码:

echo '["a","b","c","d","e"]' | jq '..|= if type == "array" then [limit(3;.[])] else . end'
[
  "a",
  "b",
  "c",
  null,
  null
]

期望它生成短数组:

[
  "a",
  "b",
  "c"
]

我使用的 JSON 又大又复杂。我的目标是将所有数组缩小到长度 3。我得到的是原始长度的数组,其中有很多空值。

有想法吗?

Trying the following code:

echo '["a","b","c","d","e"]' | jq '..|= if type == "array" then [limit(3;.[])] else . end'
[
  "a",
  "b",
  "c",
  null,
  null
]

Expect it to produce short array:

[
  "a",
  "b",
  "c"
]

JSONs I work with are big and complex. My goal is to shrink all arrays down to length 3. What I get is arrays of original length with lots of nulls.

Ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

苍景流年 2025-01-18 06:37:11

如果整体结构可能很复杂,但数组的数量和排列并不复杂(例如,没有数组本身是位置高于 3 的另一个数组的项等),则可以简单地寻址“所有数组”并缩短它们彼此独立:

(.. | arrays) |= .[:3]

但是,如果您需要涵盖这些特殊情况,则 walk 会更合适,因为它按顺序沿文档树下降,因此在截断后不会留下悬空部分:

walk(if type == "array" then .[:3] else . end)

If while the overall structure may be complex, the amount and arrangement of the arrays are not (e.g. no array is itself an item of another array at a position higher than 3, etc), you can simply address "all arrays" and shorten them independently from each other:

(.. | arrays) |= .[:3]

If, however, you need to cover those special cases, walk would be more appropriate as it descends the document tree in order and therefore will not leave over dangling parts after the trucation:

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