Home > front end >  How to segregate json file by using a field?
How to segregate json file by using a field?

Time:12-08

I have a json file like this

{
"alerts":[
  {
     "id":573983,
     "type":"EVENT",
     "name":"[IBM]: Usage Tier Changed"
  },
  {
     "id":576757,
     "type":"MANUAL",
     "name":"Root volume disk usage warning"
  }
 ]
}

I want to segregate this one file into two serparate json files based on field type:MANUAL and
type:EVENT

CodePudding user response:

You can try this.

d = {
"alerts":[
  {
     "id":573983,
     "type":"EVENT",
     "name":"[IBM]: Usage Tier Changed"
  },
  {
     "id":576757,
     "type":"MANUAL",
     "name":"Root volume disk usage warning"
  }
 ]
}

event_dict = []
manual_dict = []
for line in d.get('alerts'):
    if line.get('type') == 'MANUAL':
        manual_dict.append(line)
    elif line.get('type') == 'EVENT':
        event_dict.append(line)

print(f'event_dict -> {event_dict} \n manual_dict -> {manual_dict}')

CodePudding user response:

import itertools
data = {
"alerts":[
  {
     "id":573983,
     "type":"EVENT",
     "name":"[IBM]: Usage Tier Changed"
  },
  {
     "id":576757,
     "type":"MANUAL",
     "name":"Root volume disk usage warning"
  },
  {
     "id":5767555,
     "type":"MANUAL",
     "name":"manuel loggg"
  },
  {
     "id":57675,
     "type":"MANUAL",
     "name":"manuel loggg2"
  },
    {
     "id":573963,
     "type":"EVENT",
     "name":"[IBM]: HI"
  },
    
 ]
}

new_list = []
  
for key, group in itertools.groupby(sorted(data['alerts'], key=lambda x:x['type']), lambda x: x['type']):
    print(key   " :", list(group))

Result:

EVENT : [{'id': 573983, 'type': 'EVENT', 'name': '[IBM]: Usage Tier Changed'}, {'id': 573963, 'type': 'EVENT', 'name': '[IBM]: HI'}]
MANUAL : [{'id': 576757, 'type': 'MANUAL', 'name': 'Root volume disk usage warning'}, {'id': 5767555, 'type': 'MANUAL', 'name': 'manuel loggg'}, {'id': 57675, 'type': 'MANUAL', 'name': 'manuel loggg2'}]

Good luck

  • Related