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

时间:2019-03-19 15:59:45

标签: python python-3.x

[{...  
  {'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'},
...}]

1 个答案:

答案 0 :(得分:0)

假设您提供的json对象是数组中每个对象的格式,这是一种简单的 for-loop 方法。

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'}]
相关问题