尝试从 json 文件中删除键/值时'str'我得到对象没有属性"pop"/"del"



我有一个json文件的结构:

{
"collections": {
"tags": {
"2GvAB3TrWwJSdDeAdg4R": {
"id": "",
"aperances": 1,
"tagName": "todolist",
"__collections__": {}
}
}
}

我想要的是从"2GvAB3TrWwJSdDeAdg4R"对象(或"标签"内的对象)属性&;id&;和&;__集合__&;所以我可以有这样的对象:

{
"collections": {
"tags": {
"2GvAB3TrWwJSdDeAdg4R": {
"aperances": 1,
"tagName": "todolist",
}
}
}

这是我尝试过的代码,但使用popdel会给我一个AttributeError: 'str' object has no attribute ...

import json
with open('jsontest.json', 'r+') as f:
data = json.load(f)
for element in data:
for attibute in element:
attibute.pop('id', None)
attibute.pop('_collections', None)
with open('jsontest.json', 'w') as data_file:
data = json.dump(data, f)

感谢任何帮助,谢谢!

您访问的是for循环中的键而不是value。试后

data = {
"collections": {
"tags": {
"2GvAB3TrWwJSdDeAdg4R": {
"id": "",
"aperances": 1,
"tagName": "todolist",
"__collections__": {}
}
}
}
}
for element in data:
for tag in data[element]:
for attribute in data[element][tag]:
data[element][tag][attribute].pop('id', None)
data[element][tag][attribute].pop('_collections', None)

问题是,当您遍历字典时,默认情况下只获取键。我们可以通过打印代码中的变量来看到这一点:

for element in d:
print(element)
for attribute in element:
print(attribute)

第一个变量是一个键,即字符串,当我们迭代它时,我们得到另一个字符串,即它的每个字符:

collections
c
o
l
l
e
c
t
i
o
n
s

我解释数据的方式,我们可以只是索引"集合"。和标签",然后迭代:

for element in data:
print(element)
for attribute in element:
print(attribute)        
collections = data["collections"]
tags = collections["tags"]
for k in tags:
del(tags[k]["id"])
del(tags[k]["__collections__"])
print(data)
# {'collections': {'tags': {'2GvAB3TrWwJSdDeAdg4R': {'aperances': 1, 'tagName': 'todolist'}}}}

你完全做错了,这不是在python中迭代字典的方式。如果你有模式,你可以直接删除这样的值,然后你可以转储数据到文件。

import json
with open('jsontest.json', 'r+') as f:
data = json.load(f)
print("Orignal Data: ",data)
del data['collections']['tags']['2GvAB3TrWwJSdDeAdg4R']['id']
del data['collections']['tags']['2GvAB3TrWwJSdDeAdg4R']['__collections__']
print("Updated Data: ",data)

你也可以这么做

with open(r'jsontest.json', 'r+') as f:
data = json.load(f)
del(data["collections"]["tags"]["2GvAB3TrWwJSdDeAdg4R"]['id'])
del(data["collections"]["tags"]["2GvAB3TrWwJSdDeAdg4R"]['__collections__'])

结果:

{'collections': {'tags': {'2GvAB3TrWwJSdDeAdg4R': {'aperances': 1, 'tagName': 'todolist'}}}}

最新更新