在Json File Python中删除对象

问题描述

我有一个json文件

[{"uid": x,"username": "x","firstname": "x","lastname": "x","access_hash": x},{"uid": y,"username": "y","firstname": "y","lastname": "y","access_hash": y}]

并且我想在im循环中删除对象{“ uid [...]” access-hash“:x}

我有以下代码

 try:
                user_to_add = InputPeerUser(user['uid'],user['access_hash'])
                add = await client(InvitetochannelRequest(target_group_entity,[user_to_add]))
                print(gr+'Added ',str(user['uid']))
                #remove the object where I used uuid acces_hash and so on

我希望有人能帮助我,并提前联系!

解决方法

您可以使用pop()

my_dict = [{"uid": 'x',"username": "x","firstname": "x","lastname": "x","access_hash": 'x'},{"uid": 'y',"username": "y","firstname": "y","lastname": "y","access_hash": 'y'}]

for i in range(0,len(my_dict)-1):
    if my_dict[i]['uid'] == 'x':
        my_dict.pop(i)
print(my_dict)
,

请在将来尝试阅读Stack Overflow guidelines for questions posting,以便对您的问题进行清晰而完整的描述。通常,提供上下文有很大帮助。

关于您的问题,我会做一些假设。第一个是您要遍历用户对象的数组,第二个是每个对象都是唯一的。

您应该使用pop() List方法,因为要删除刚添加到通道中的用户对象。

一个简单的例子是:

while(len(users_list)>0):
     users.pop(0) # You are removing the current object of the users_list.

由于要从列表中删除对象,因此从逻辑上讲,对象的长度将开始减小,直到打破while条件。