如何从JSON数组中删除值?

时间:2017-09-01 10:51:59

标签: python json

    path = os.path.dirname(os.path.realpath(__file__))
    if os.path.exists(path + '/nomore.json'):
        blacklist = json.loads(open("%s/nomore.json" % (path)).read())
        if cmd.lower() == "add":
            try:
                username = await self.bot.get_user_info(usr)
                blacklist["blacklist"].append(int(usr))
                json.dump(blacklist, (open("%s/nomore.json" % (path), 'w')))
                await self.bot.say('`%s` added to blacklist' % (username))
            except Exception as e:
                await self.bot.say(e)
        elif cmd.lower() == "remove":
            try:
                for ids in blacklist["blacklist"]:
                    if ids == int(usr):
                        blacklist["blacklist"].remove[ids]
                        json.dump(blacklist, (open("%s/nomore.json" % (path), 'w')
                        await self.bot.say('Remove invoked')
            except Exception as e:
                await self.bot.say(e)

我正在使用.append()向JSON对象添加值,但我不确定通过值从数组中删除值的正确方法是什么。

这就是JSON文件的样子:

{"blacklist": [225915965769121792, 272445925845106700]}

3 个答案:

答案 0 :(得分:1)

嗯......如果你的json是blacklist,那么为什么不这样做呢?

# If you know the value to be removed:
blacklist['blacklist'].remove(225915965769121792)
# Or if you know the index to be removed (pop takes an optional index, otherwise defaults to the last one):
blacklist['blacklist'].pop()
# Or
del blacklist['blacklist'][0]  # 0 or any other valid index can be used.

答案 1 :(得分:0)

https://docs.python.org/3/tutorial/datastructures.html

blacklist["blacklist"].pop(i); # `i` is the index you want to remove

答案 2 :(得分:0)

lst = [100, 200, 300, 400]

idx = lst.index(300)
removed_item = lst.pop(idx)

print(removed_item)
print(lst)