当尝试从JSON对象中删除值时,为什么我收到错误'Unicode'Object不支持项目删除&Quot;?

2022-02-20 00:00:00 python dictionary json

问题描述

我试图遍历对象列表,从每个对象中删除一个元素。每个对象都是新的一行。然后,我尝试按原样保存新文件,而不保存对象中包含的元素。

{
    "business_id": "fNGIbpazjTRdXgwRY_NIXA",
    "full_address": "1201 Washington Ave
Carnegie, PA 15106",
    "hours": {
        "Monday": {
            "close": "23:00",
            "open": "11:00"
        },
        "Tuesday": {
            "close": "23:00",
            "open": "11:00"
        },
        "Friday": {
            "close": "23:00",
            "open": "11:00"
        },
        "Wednesday": {
            "close": "23:00",
            "open": "11:00"
        },
        "Thursday": {
            "close": "23:00",
            "open": "11:00"
        },
        "Saturday": {
            "close": "23:00",
            "open": "11:00"
        }
    },
    "open": true,
    "categories": ["Bars", "American (Traditional)", "Nightlife", "Lounges", "Restaurants"],
    "city": "Carnegie",
    "review_count": 7,
    "name": "Rocky's Lounge",
    "neighborhoods": [],
    "longitude": -80.0849416,
    "state": "PA",
    "stars": 4.0,
    "latitude": 40.3964688,
    "attributes": {
        "Alcohol": "full_bar",
        "Noise Level": "average",
        "Music": {
            "dj": false
        },
        "Attire": "casual",
        "Ambience": {
            "romantic": false,
            "intimate": false,
            "touristy": false,
            "hipster": false,
            "divey": false,
            "classy": false,
            "trendy": false,
            "upscale": false,
            "casual": false
        },
        "Good for Kids": true,
        "Wheelchair Accessible": true,
        "Good For Dancing": false,
        "Delivery": false,
        "Dogs Allowed": false,
        "Coat Check": false,
        "Smoking": "no",
        "Accepts Credit Cards": true,
        "Take-out": true,
        "Price Range": 1,
        "Outdoor Seating": false,
        "Takes Reservations": false,
        "Waiter Service": true,
        "Wi-Fi": "free",
        "Caters": false,
        "Good For": {
            "dessert": false,
            "latenight": false,
            "lunch": false,
            "dinner": false,
            "brunch": false,
            "breakfast": false
        },
        "Parking": {
            "garage": false,
            "street": false,
            "validated": false,
            "lot": true,
            "valet": false
        },
        "Has TV": true,
        "Good For Groups": true
    },
    "type": "business"
}

我需要删除小时元素中包含的信息,但是这些信息并不总是相同的。有些包含所有日期,有些仅包含一天或两天信息。

这是我尝试过的代码:

import json

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

但是,运行代码时出现错误:

TypeError:‘Unicode’对象不支持项删除


解决方案

假设您要覆盖同一文件:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None)可能就是您要找的,如果我理解您的要求的话。因为它将删除hours项(如果存在),如果不存在则不会失败。

不过,我不确定我是否理解为什么小时键是否包含几天对您有影响,因为您只是想去掉整个键/值对,对吗?

现在,如果您确实希望使用del而不是pop,下面是如何使您的代码工作的方法:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

如果要将其写入其他文件,只需更改第二个open语句中的文件名。

您可能已经注意到,我必须更改缩进,以便在数据清理阶段关闭该文件,并且可以在结束时覆盖该文件。

with是所谓的上下文管理器,无论它提供什么(这里是data_file文件描述符),仅在该上下文中可用。这意味着with挡路的缩进一结束,文件就会关闭,上下文以及变为无效/过时的文件描述符也会结束。

如果不这样做,您将无法在写入模式下打开文件并获取要写入的新文件描述符。

相关文章