Home > Mobile >  How to Group By within Object in jq
How to Group By within Object in jq

Time:11-15

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.

CodePudding user response:

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