Python 删除 JSON 对象中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36606930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:05:48  来源:igfitidea点击:

Delete an element in a JSON object

pythonjsonobject

提问by Bradley

I am trying to loop through a list of objects deleting an element from each object. Each object is a new line. I am trying to then save the new file as is without the element contained within the objects. I know this is probably a simple task but I cannot not seem to get this work. Would be grateful if somebody could offer a hand. Thanks.

我正在尝试遍历从每个对象中删除一个元素的对象列表。每个对象都是一个新行。我试图然后按原样保存新文件,而不包含对象中包含的元素。我知道这可能是一项简单的任务,但我似乎无法完成这项工作。如果有人可以伸出援手,将不胜感激。谢谢。

{
"business_id": "fNGIbpazjTRdXgwRY_NIXA",
"full_address": "1201 Washington Ave\nCarnegie, 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"

}

}

I need to remove the information contained within the hours element however the information is not always the same. Some contain all the days and some only contain one or two day information. The code i've tried to use is Pyton that I have search throughout the day to use with my problem. I am not very skilled with Python. Any help would be appreciated.

我需要删除 hours 元素中包含的信息,但是信息并不总是相同的。有些包含所有天数,有些只包含一两天的信息。我尝试使用的代码是 Pyton,我整天都在搜索它以解决我的问题。我对 Python 不是很熟练。任何帮助,将不胜感激。

import json

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

Sorry Just to Add the error I am getting when running the code is TypeError: 'unicode' object does not support item deletion

抱歉,只是添加我在运行代码时遇到的错误是 TypeError: 'unicode' object does not support item delete

回答by Anthony Perot

Let's assume you want to overwrite the same file:

假设您要覆盖同一个文件:

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)is probably what you where looking for, if I understood your requirements. Because it will remove the hourskey if present and will not fail if not present.

dict.pop(<key>, not_found=None)如果我了解您的要求,可能就是您正在寻找的内容。因为它会删除hours密钥(如果存在)并且如果不存在则不会失败。

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

但是,我不确定我是否理解为什么 hours 键是否包含某些天对您有影响,因为您只想摆脱整个键/值对,对吗?

Now, if you really want to use delinstead of pop, here is how you could make your code work:

现在,如果你真的想使用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)

EDITSo, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

编辑因此,如您所见,我添加了将数据写回文件的代码。如果要将其写入另一个文件,只需在第二个 open 语句中更改文件名即可。

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

正如您可能已经注意到的那样,我不得不更改缩进,以便文件在数据清理阶段已关闭,并且可以在最后被覆盖。

withis what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLYwithin that context. It means that as soon as the indentation of the withblock ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

with就是所谓的上下文管理器,它提供的任何内容(此处为 data_file 文件描述符)在该上下文中可用。这意味着一旦with块的缩进结束,文件就会关闭,上下文结束,文件描述符也变得无效/过时。

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

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

I hope it's clear enough...

我希望它足够清楚...

SECOND EDIT

第二次编辑

This time, it seems clear that you need to do this:

这一次,您显然需要这样做:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))