简体   繁体   English

如何通过数组删除 JSON object? (Python)

[英]How can I remove a JSON object via array? (Python)

I know the title looks a little confusing but once I share the code you'll know what I am talking about.我知道标题看起来有点混乱,但一旦我分享代码,你就会知道我在说什么。 I am fairly new to working with JSON and Python overall.总的来说,我对使用 JSON 和 Python 还是很陌生。 I'm trying to make a grocery list program with 3 simple commands: list, add, and remove.我正在尝试使用 3 个简单的命令制作一个购物清单程序:列出、添加和删除。 List will list all of your groceries that you added via add. List 将列出您通过 add 添加的所有杂货。 Remove removes an item by name. Remove 按名称删除项目。 This is where I'm having trouble.这就是我遇到麻烦的地方。 This is what my setup looks like:这是我的设置的样子:

{"grocery_list": 
   [{"itemname": "Milk"},
   {"itemname": "Bread"},
   {"itemname": "Bacon"}]
}

This is my remove function and data:这是我删除 function 和数据:

with open('groceriesjson.json','r') as data_file:
        data = json.load(data_file)
def removeitem(item):
        global data
        for i in range(len(data)):
            if data[i]["itemname"] == item:
                data.pop(i)
                print("Successfully removed from your list.")
                main()

When I run the program, I get this error:当我运行程序时,我得到这个错误:

Traceback (most recent call last):
  File "C:\Users\me\Desktop\test.py", line 48, in <module>
    main()
  File "C:\Users\me\Desktop\test.py", line 44, in main
    removeitem(toremove)
  File "C:\Users\me\Desktop\test.py", line 18, in removeitem
    if data[i]["itemname"] == item:
 KeyError: 0

I have also tried using range(1,len(data)) but when I run it nothing happens.我也尝试过使用range(1,len(data))但是当我运行它时没有任何反应。 If you need any more snippets of code or anything else please comment.如果您需要更多代码片段或其他任何内容,请发表评论。 Thanks a lot非常感谢

You can instead use a list comprehension您可以改为使用list comprehension

values = {
    "grocery_list": [
        {"itemname": "Milk"},
        {"itemname": "Bread"},
        {"itemname": "Bacon"}
    ]
}

print({
    "grocery_list": 
        [v for v in values['grocery_list'] if v['itemname'] != 'Milk']
})

You have failed to test your program in stages;您未能分阶段测试您的程序; you now have multiple mistakes to correct.您现在有多个错误需要纠正。 See this lovely reference for debugging help .请参阅这个可爱的参考以获取 调试帮助 If nothing else, insert frequent print commands to check your assumptions about data types and values.如果不出意外,请插入频繁的print命令来检查您对数据类型和值的假设。

You do not have a "JSON object";您没有“JSON 对象”; you have a Python dict .你有一个 Python dict For a better example, remove the input sequence and replace it with the hard-coded dict equivalent.举个更好的例子,删除输入序列并将其替换为硬编码的 dict 等效项。 The first step of debugging is to isolate the problem, and this demonstrates that the input is independent.调试的第一步是隔离问题,这表明输入是独立的。

Now, look at your structure: the dict has one entry, keyed by the string "grocery_list".现在,看看你的结构:字典有一个条目,由字符串“grocery_list”键入。 Your immediate error is that you tried to access this as a list , using subscript 0. This would work well with the next level down, data["grocery_list"], as that is a list.您的直接错误是您尝试使用下标 0 将其作为list访问。这适用于下一级数据 [“grocery_list”],因为那一个列表。

Next, you will run into problems when you alter a list while you iterate over it.接下来,当您在迭代列表时更改列表时遇到问题。 See the related questions on that topic for pointers.请参阅有关该主题的相关问题以获取指示。 The "normal" way is to use a list comprehension, as you see in Sushanth 's answer.正如您在Sushanth的回答中看到的那样,“正常”的方法是使用列表理解。

You call a routine main from within your removal loop;您从删除循环中调用例程main this is almost certainly a mistake, especially if that routine is, indeed, your main program.这几乎可以肯定是一个错误,特别是如果该例程确实是您的主程序。 Put in print statements and follow the logic to see how this actually works.放入print语句并按照逻辑查看其实际工作原理。

Maybe something like this:也许是这样的:

def removeitem(del_item):
        global data
        grocery_list = data['grocery_list']

        for i, item in enumerate(grocery_list):
            if item["itemname"] == del_item:
                grocery_list.pop(i)
                print("Successfully removed from your list.")
                break

        return grocery_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM