Home > Back-end >  jq: limitting all arrays in a complex json
jq: limitting all arrays in a complex json

Time:03-03

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?

CodePudding user response:

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)
  • Related