【问题标题】:Removing JSON property in array of objects with Python + Inverse使用 Python + Inverse 删除对象数组中的 JSON 属性
【发布时间】:2016-11-21 18:15:10
【问题描述】:

样本数据:

[{"title": "foo", "imageData": "xyz123"}, {"title": "bar", "imageData": "abc123"}, {"title": "baz", "imageData": "def456"}]

这将删除不需要的密钥,删除来自here

import json

with open('data.json') as json_data:
    data = json.load(json_data)
    for element in data: 
        del element['imageData'] 

这个命令del element['imageData']的反义词是什么。所以我想删除除imageData 键之外的所有内容。

【问题讨论】:

  • 是否要将数据写回json文件?

标签: python json


【解决方案1】:

您可以使用列表推导来创建一个仅包含感兴趣元素的新列表:

import json

with open('data.json') as json_data:
    data = json.load(json_data)
    new_data = [{'imageData': element['imageData']} for element in data]

【讨论】:

    【解决方案2】:

    你可以这样做:

    temp = data['imageData']
    data.clear()
    data['imageData'] = temp
    

    生成的名为 data 的字典将仅包含键 imageData 及其关联值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 2021-01-04
      • 2015-09-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多