如何通过python删除json中的冗余内容?

问题描述 投票:0回答:1
[{...  
  {'adminregion': {'id': 'SAS', 'iso2code': '8S', 'value': 'South Asia'},
      'capitalCity': 'Kabul',
      'id': 'AFG',
      'incomeLevel': {'id': 'LIC', 'iso2code': 'XM', 'value': 'Low income'},
      'iso2Code': 'AF',
      'latitude': '34.5228',
      'lendingType': {'id': 'IDX', 'iso2code': 'XI', 'value': 'IDA'},
      'longitude': '69.1761',
      'name': 'Afghanistan',
      'region': {'id': 'SAS', 'iso2code': '8S', 'value': 'South Asia'}},
...}]

以上是我从API收集的世界银行的JSON文件的一部分,但我不需要每一列。我想知道如何删除我实际上不需要的列?

我很满意以下结果:

[{...  
  {
      'id': 'AFG',
      'incomeLevel': 'Low income',
      'name': 'Afghanistan',
      'region': 'South Asia'},
...}]
python python-3.x
1个回答
0
投票

这是一个简单的for循环方法,因为您提供的json对象是数组中每个对象的格式。

res = []

for item in data:
    id_ = item.get('id')
    income = item.get('incomeLevel').get('value')
    name = item.get('name')
    region = item.get('region').get('value')
    final = {'id': id_, 'incomeLevel': income, 'name': name, 'region': region}
    res.append(final)

print(res)

[{'id': 'AFG',
  'incomeLevel': 'Low income',
  'name': 'Afghanistan',
  'region': 'South Asia'}]

或者另一种方法是:

keys = ['id', 'incomeLevel', 'name', 'region']
res = []

for item in data:
    out = {}
    for k, v in item.items():
        if k in keys:
            if isinstance(v, dict):
                out.update({k: v.get('value')})
            else:
                out.update({k: v})
    res.append(out)

print(res)

[{'id': 'AFG',
  'incomeLevel': 'Low income',
  'name': 'Afghanistan',
  'region': 'South Asia'}]
© www.soinside.com 2019 - 2024. All rights reserved.