Python JSON -如果只有“key”存在,则删除“value”键及其值

lnvxswe2  于 2023-10-21  发布在  Python
关注(0)|答案(2)|浏览(143)

我有一个JSON数据。如果只有“key”存在,我想删除“value”键。
我想删除“工作”和“暴徒没有”,并保持其余的,因为它是。
实际产量:

{
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        },
        {
          "key": "Job"
        },
        {
          "key": "Mob No"
        }
      ]
    }
    ]
}

预期输出:

{
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        }
      ]
    }
]
}

我尝试使用下面的函数:

def remove_empty_values(data):
    if isinstance(data, dict):
        for key, value in list(data.items()):
            if isinstance(value, list) or isinstance(value, dict):
                remove_empty_values(value)
            elif key == "attributes":
                for detail in value:
                    if isinstance(detail, dict) and "key" in detail and "value" in detail:
                        if "key" in detail and "value" in detail:
                            if not detail["value"]:
                                del detail["value"]
            elif key == "value" and not value:
                del data[key]

通过在json.loads中加载调用上面的函数,但输出为None。
我不知道出了什么问题。

sz81bmfz

sz81bmfz1#

你只需要一个列表解析来替换'details'列表,如下所示:

import json # only needed for output presentation

d = {
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        },
        {
          "key": "Job"
        },
        {
          "key": "Mob No"
        }
      ]
    }
    ]
}

for m in d.get('Main', []):
    if 'details' in m:
        m['details'] = [_d for _d in m['details'] if len(_d) != 1]

print(json.dumps(d, indent=2))

输出:

{
  "Name": "Nelson",
  "Country": "India",
  "Main": [
    {
      "Property": "House",
      "details": [
        {
          "key": "No",
          "value": "1"
        },
        {
          "key": "Place",
          "value": "KAR"
        }
      ]
    }
  ]
}

注:

检查“details”键的存在只是为了使代码更健壮。对于问题中显示的数据,这是不必要的。
因此,如果你对字典(JSON)的结构和内容有很高的信心,那么它只是:

for m in d['Main']:
    m['details'] = [_d for _d in m['details'] if len(_d) != 1]
rjzwgtxy

rjzwgtxy2#

如果json文件的结构是固定的,你可以这样做。

import json

data = json.loads(json_str)
for i in len(data["Main"]):
    data["Main"][i]["details"] = [datum for datum in data["Main"][i]["details"] if datum["key"] not in keys]
output = json.dumps(data)

相关问题