Python - 删除"空"来自已解码的JSON数据的值(' []''""')

时间:2018-04-16 01:27:31

标签: python json

在Python脚本中,我运行json_decoded = json.load(file)会产生以下JSON数据:

json_decoded = {
  "data": {
    "keyA": [
      {
        "subkeyA1": "valueA1",
        "subkeyA2": "valueA2"
      },
      {
        "subkeyA3": ""
      }
    ],
    "keyB": []
  }
}

我想删除所有 []""("空")键值对,以便:

json_decoded = {
  "data": {
    "keyA": [
      {
        "subkeyA1": "valueA1",
        "subkeyA2": "valueA2"
      }
    ]
  }
}

我怎么能拥有它?

注意:我是Python的新手(v2.7.3)。

1 个答案:

答案 0 :(得分:1)

您可以使用递归来遍历结构:

json_decoded = {'data': {'keyA': [{'subkeyA1': 'valueA1', 'subkeyA2': 'valueA2'}, {'subkeyA3': ''}], 'keyB': []}}
def remove_empty(d):
  final_dict = {}
  for a, b in d.items():
     if b:
       if isinstance(b, dict):
         final_dict[a] = remove_empty(b)
       elif isinstance(b, list):
         final_dict[a] = list(filter(None, [remove_empty(i) for i in b]))
       else:
         final_dict[a] = b
  return final_dict

print(remove_empty(json_decoded))

输出:

{'data': 
  {'keyA': 
     [{'subkeyA1': 'valueA1', 
       'subkeyA2': 'valueA2'}
    ]
  }
}