jq:限制复杂 json 中的所有数组
尝试以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果整体结构可能很复杂,但数组的数量和排列并不复杂(例如,没有数组本身是位置高于 3 的另一个数组的项等),则可以简单地寻址“所有数组”并缩短它们彼此独立:
但是,如果您需要涵盖这些特殊情况,则
walk
会更合适,因为它按顺序沿文档树下降,因此在截断后不会留下悬空部分: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:
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: