user3819295
user3819295

Reputation: 861

JSON GroupBy 2 attributes - Python

I'm facing some difficulties while trying to aggregate JSON attributes. Basically, what I'm trying to do is to groupBy the objects in 'InputTable' array by two attributes 'To' and 'TemplateName'. The JSON template looks as follows:

x = {
        "InputTable" : 
        [
            {
                "ServerName":"ServerOne",
                "To":"David", 
                "CC":"Oren", 
                "TemplateName":"LinuxVMOne", 
            },
            {
                "ServerName":"ServerTwo",
                "To":"David", 
                "CC":"", 
                "TemplateName":"LinuxVMOne", 
            },
            {
                "ServerName":"ServerThree",
                "To":"David", 
                "CC":"", 
                "TemplateName":"LinuxVMTwo", 
            },
            {
                "ServerName":"ServerFour",
                "To":"Sam", 
                "CC":"Samer", 
                "TemplateName":"LinuxVMOne", 
            }   
        ]
}

Expected results would look something like this, list of lists with grouped objects:

[ 
   [

      {
                "ServerName":"ServerOne",
                "To":"David", 
                "CC":"Oren", 
                "TemplateName":"LinuxVMOne"
      },
      {
                "ServerName":"ServerTwo",
                "To":"David", 
                "CC":"", 
                "TemplateName":"LinuxVMOne", 
      },

  ],

  [
      {
                "ServerName":"ServerThree",
                "To":"David", 
                "CC":"", 
                "TemplateName":"LinuxVMTwo", 
      },

  ],

  [
      {
                "ServerName":"ServerFour",
                "To":"Sam", 
                "CC":"Samer", 
                "TemplateName":"LinuxVMOne", 
      }
  ] 



]

]

Is it possible to do it without using pandas? Thank you.

Upvotes: 1

Views: 47

Answers (1)

Hippolyte BRINGER
Hippolyte BRINGER

Reputation: 863

This code works:

But I think we can do a code more cleaner !

y = []
for i in x["InputTable"]:
    if len(y) == 0:
        y.append([i])
    else:
        for j in y:
            if len(j) > 0:
                if j[0]["To"] == i["To"] and j[0]["TemplateName"] == i["TemplateName"]:
                    j.append(i)
                    break
                else:
                    y.append([i])
                    break   
            else:
                y.append([i])
                break

Upvotes: 2

Related Questions