Search code examples
jsonnestedjqellipsis

How to remove or ignore values from certain nesting level with jq


I have a deeply nested JSON, which is too large to look through; I want to remove all items from a certain level of nesting, preferably with jq.

Say, the JSON is:

{
  "paging": {
    "next": "items?page=12",
    "previous": "items?page=10"
  },
  "hits": {
    "total": 10200,
    "max_score": 1,
    "hits": [
      {
        "id": 1337,
        "really large struct 1": "with long and complexed nested values"
      },
      {
        "id": 1338,
        "really large struct 1": "with long and complexed nested values"
      }
    ]
  },
  "took": 11,
  "timed_out": false
}

In this example, I want to omit everything under .hits.hits, maybe replace it with an ellipsis (…) or simply ignore it. A good alternative would be to render only the id value in the example.

The fields like paging, took, and timed_oud are examples and could change, or be a rather long and wieldy list, so simply allowlisting (whitelisting) all stuff that should stay is not an option: I want to filter out a certain depth and not show that; filtering on certain denylisted (blacklisted) items like removing all .hits.hits.* is OK, though.

I've tried jq '.' | cut -c1-40 and that removes the need for horizontal scrolling and/or wrapping, but not the long vertical scrolling.


Solution

  • Update all members of .hits.hits to leave only the id field using the program below, I guess this is what you're looking for.

    .hits.hits[] |= {id}
    

    Online demo