Skip to content
Advertisement

How to Group By within Object in jq

I have this JSON Object

{
    "id_1": {
        "day_1": {
            "loc_sec": 886,
            "int_sec": null
        }
    },
    "id_1": {
        "day_2": {
            "loc_sec": 575,
            "int_sec": null
        }
    },
    "id_2": {
        "day_1": {
            "loc_sec": 140,
            "int_sec": null
        }
    },
    "id_2": {
        "day_2": {
            "loc_sec": 138,
            "int_sec": null
        }
    }
}

And I want an output like this

{
    "id_1": {
        "day_1": {
            "loc_sec": 886,
            "int_sec": null
        },
        "day_2": {
            "loc_sec": 575,
            "int_sec": null
        }
    },
    "id_2": {
        "day_1": {
            "loc_sec": 140,
            "int_sec": null
        },
        "day_2": {
            "loc_sec": 138,
            "int_sec": null
        }
    }
}

How do I achieve this with bash script and jq? This seems to be like a group by functionality, but I’m unable to figure it out.

Advertisement

Answer

Here’s a solution using jq’s –stream option:

jq -n --stream '
  def stream:
    foreach ((inputs | select(length==2)), null) as $kv (null;
      if $kv == null then .emit = .value
      else .emit = null
      | $kv[0][0] as $k
      | if .k and ($k != .k) 
        then .emit = .value | .value = null 
        else . 
        end
      | .value |= setpath($kv[0]; $kv[1])
      | .k = $k
      end;
    select(.emit).emit);

  [stream] | add
' input.json
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement