【问题标题】:How to remove a value from a JSON array?如何从 JSON 数组中删除一个值?
【发布时间】:2017-09-01 10:51:58
【问题描述】:
    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]}

【问题讨论】:

  • 什么是await
  • 在您的问题中添加输入 josn

标签: python json


【解决方案1】:

嗯...如果blacklist 是您的json,那么为什么不执行以下操作?

# 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.

【讨论】:

  • blacklist['blacklist'].remove(225915965769121792) 正是我想要的。干杯伙伴。
  • @Okiic。我的荣幸 :) 但我很好奇 - await 是什么?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    lst = [100, 200, 300, 400]
    
    idx = lst.index(300)
    removed_item = lst.pop(idx)
    
    print(removed_item)
    print(lst)
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2023-03-31
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2015-12-19
      • 1970-01-01
      相关资源
      最近更新 更多