【问题标题】:How to segregate json file by using a field?如何使用字段分隔 json 文件?
【发布时间】:2022-01-13 09:08:39
【问题描述】:

我有一个这样的 json 文件

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

我想根据字段类型将这个文件分成两个单独的 json 文件:MANUAL 和
类型:事件

【问题讨论】:

  • 你尝试这样做的困难究竟是什么?

标签: python json python-3.x


【解决方案1】:

你可以试试这个。

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}')

【讨论】:

  • 出现以下错误,root@acierate1:~# python3 div.py Traceback(最近一次调用最后一次):文件“div.py”,第 42 行,在 中,用于 f.get 中的行('alerts'): AttributeError: '_io.TextIOWrapper' 对象没有属性 'get'
  • 我假设您的输入是 dict,粘贴您的完整数据,根据您粘贴的输入,它的工作,顺便说一句,仅仅因为您的输入与您粘贴的不同,因此投入答案不会鼓励人们为了帮助你,人们不一定要帮助你。尝试自己做这件事,而不是要求别人为你做这件事。
【解决方案2】:
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))

结果:

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'}]

祝你好运

【讨论】:

  • 我希望在 2 个单独的文件中输出如下所示。{ "alerts":[ { "id":573983, "type":"EVENT", "name":"[IBM ]: Usage Tier Changed" } ] } { "alerts":[ { "id":576757, "type":"MANUAL", "name":"Root volume disk usage warning" } ] }
  • 那么不要像那样使用打印;使用 open('data.txt', 'w') 作为输出文件: json.dump(data, outfile)
猜你喜欢
  • 2017-10-20
  • 2011-08-27
  • 2012-02-19
  • 2012-01-04
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多