Python 属性错误:';int';对象没有属性';项目';使用json和字典时
我有一个代码,其目的是将Python 属性错误:';int';对象没有属性';项目';使用json和字典时,python,json,dictionary,Python,Json,Dictionary,我有一个代码,其目的是将“$oid”,“$id”键替换为不带$符号的键。执行此操作的函数获取一个字典并返回一个新字典。我的文件包含几个“行”,这就是我需要进行解析的原因(在代码下面我将发布一个数据示例): 对于以下数据示例,它是有效的(我最初认为错误是因为true或数值): 它返回: {"_id": "5d1dc6ba0d27b66b64575bc5", "quiz": [], "name": "MyNam
“$oid”
,“$id”
键替换为不带$
符号的键。执行此操作的函数获取一个字典并返回一个新字典。我的文件包含几个“行”,这就是我需要进行解析的原因(在代码下面我将发布一个数据示例):
对于以下数据示例,它是有效的(我最初认为错误是因为true
或数值):
它返回:
{"_id": "5d1dc6ba0d27b66b64575bc5", "quiz": [], "name": "MyName", "startDate": "2019-07-08T10:00:00Z", "service": "5d160dc22549bc51860b2736", "__v": 0}
{"_id": "5d5be8a3221257336792a5ad", "quiz": [], "name": "YourName", "repeatable": true, "alertText": "3", "startDate": "2019-08-19T10:00:00Z", "service": "5cf8f93af70b3e01bb970fe6", "__v": 0}
下面有一个很长的示例行,其中代码停止工作,它给了我AttributeError:“int”对象没有属性“items”
。是因为这些嵌套字典吗?我可以用我的代码做什么
{"_id":{"$oid":"5ae9595a97c91e0d18d50d82"},"name":"sample","settings":[{"title":"sampletitle","types":["easy","hard"]},{"title":"sampletitle2","types":["easy","hard"]}],"video":"https://www.youtube.com/watch?v=vvvvvvv","testTypes":[{"$oid":"5cad910"},{"$oid":"5cad9"}],"storage":"https://s3.eu-central-2.amazonaws.com/smthsmthsmth/","tempSettings":{"edit":true,"max":2,"min":1},"completed":true,"url":"https://something.com/pic.png","StartedAt":{"$date":"2021-04-01T06:31:41.786Z"}}
整个错误:
AttributeError Traceback (most recent call last)
<ipython-input-12-78e23a72f1de> in <module>
24
25 for d in dicts:
---> 26 new_d = key_replacer(d)
27 json_string=json.dumps(new_d)
28 print(json_string)
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
11 tmp = []
12 for itm in v:
---> 13 tmp.append(key_replacer(itm))
14 v = tmp
15 new_dictionary[k] = v
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
11 tmp = []
12 for itm in v:
---> 13 tmp.append(key_replacer(itm))
14 v = tmp
15 new_dictionary[k] = v
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
3 def key_replacer(dictionary):
4 new_dictionary = {}
----> 5 for k, v in dictionary.items():
6 if k in ('$oid', '$date'):
7 return v
AttributeError: 'str' object has no attribute 'items'
AttributeError回溯(最近一次调用)
在里面
24
25对于dicts中的d:
--->26新的\u d=钥匙更换件(d)
27 json_string=json.dumps(新的)
28打印(json_字符串)
in key_replacer(字典)
11 tmp=[]
12对于在v中的itm:
--->13 tmp.附加(钥匙更换器(itm))
14 v=tmp
15新字典[k]=v
in key_replacer(字典)
11 tmp=[]
12对于在v中的itm:
--->13 tmp.附加(钥匙更换器(itm))
14 v=tmp
15新字典[k]=v
in key_replacer(字典)
3 def钥匙更换器(字典):
4新字典={}
---->5表示字典中的k,v.items():
6如果k in(“$oid”,“$date”):
7返回v
AttributeError:“str”对象没有属性“items”
“类型”:[“容易”,“难”]
在您的数据中,您的代码尝试调用键替换器(“容易”)
,“容易”
未被指定
代码:
结果:
{"_id": "5d1dc6ba0d27b66b64575bc5", "quiz": [], "name": "MyName", "startDate": "2019-07-08T10:00:00Z", "service": "5d160dc22549bc51860b2736", "__v": 0}
{"_id": "5d5be8a3221257336792a5ad", "quiz": [], "name": "YourName", "repeatable": true, "alertText": "3", "startDate": "2019-08-19T10:00:00Z", "service": "5cf8f93af70b3e01bb970fe6", "__v": 0}
{"_id": "5ae9595a97c91e0d18d50d82", "name": "sample", "settings": [{"title": "sampletitle", "types": ["easy", "hard"]}, {"title": "sampletitle2", "types": ["easy", "hard"]}], "video": "https://www.youtube.com/watch?v=vvvvvvv", "testTypes": ["5cad910", "5cad9"], "storage": "https://s3.eu-central-2.amazonaws.com/smthsmthsmth/", "tempSettings": {"edit": true, "max": 2, "min": 1}, "completed": true, "url": "https://something.com/pic.png", "StartedAt": "2021-04-01T06:31:41.786Z"}
始终将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图,也不是指向外部门户的链接)进行讨论(不是评论)。还有其他有用的信息。如果错误显示哪一行出现问题,则首先可以使用
print()
,print(type())
查看此行变量中的内容。看起来你们期望字典,但你们得到的是整数。也许你用错了数据。您可以使用print()
在获取列表时检查变量字典中的内容,然后在列表中的每个元素上运行key\u replacer
,用于v:
中的itm-,但如果获取带有数字或字符串的列表,而不是带有字典的列表,则此操作将不起作用。在尝试使用key\u replacer()
@furas谢谢你,我编辑了这篇文章之前,你应该检查一下从列表中得到了什么。我在v
中为项打印之后,得到了{'title':'sampletitle','types':['easy','hard']}easy
的确,我得到了一个dict和一个字符串,但为什么?为什么?→ 这是数据的内容,没有具体的“为什么”
AttributeError Traceback (most recent call last)
<ipython-input-12-78e23a72f1de> in <module>
24
25 for d in dicts:
---> 26 new_d = key_replacer(d)
27 json_string=json.dumps(new_d)
28 print(json_string)
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
11 tmp = []
12 for itm in v:
---> 13 tmp.append(key_replacer(itm))
14 v = tmp
15 new_dictionary[k] = v
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
11 tmp = []
12 for itm in v:
---> 13 tmp.append(key_replacer(itm))
14 v = tmp
15 new_dictionary[k] = v
<ipython-input-12-78e23a72f1de> in key_replacer(dictionary)
3 def key_replacer(dictionary):
4 new_dictionary = {}
----> 5 for k, v in dictionary.items():
6 if k in ('$oid', '$date'):
7 return v
AttributeError: 'str' object has no attribute 'items'
import json
def key_replacer(dictionary):
new_dictionary = {}
for k, v in dictionary.items():
if k in ('$oid', '$date'):
return v
elif isinstance(v, dict):
v = key_replacer(v)
elif isinstance(v, list):
tmp = []
for itm in v:
if isinstance(itm, dict):
tmp.append(key_replacer(itm))#you try to call key_replacer with a string "easy" here, so you got a AttributeError: 'int' object has no attribute 'items'
else:
tmp.append(itm)
v = tmp
new_dictionary[k] = v
return new_dictionary
def parse_ndjson(data):
return [json.loads(l) for l in data.splitlines()]
with open('C:\\Windows\\files\\test.json', 'r', encoding="utf8") as handle:
data = handle.read()
dicts = parse_ndjson(data)
for d in dicts:
new_d = key_replacer(d)
json_string=json.dumps(new_d)
print(json_string)
{"_id": "5d1dc6ba0d27b66b64575bc5", "quiz": [], "name": "MyName", "startDate": "2019-07-08T10:00:00Z", "service": "5d160dc22549bc51860b2736", "__v": 0}
{"_id": "5d5be8a3221257336792a5ad", "quiz": [], "name": "YourName", "repeatable": true, "alertText": "3", "startDate": "2019-08-19T10:00:00Z", "service": "5cf8f93af70b3e01bb970fe6", "__v": 0}
{"_id": "5ae9595a97c91e0d18d50d82", "name": "sample", "settings": [{"title": "sampletitle", "types": ["easy", "hard"]}, {"title": "sampletitle2", "types": ["easy", "hard"]}], "video": "https://www.youtube.com/watch?v=vvvvvvv", "testTypes": ["5cad910", "5cad9"], "storage": "https://s3.eu-central-2.amazonaws.com/smthsmthsmth/", "tempSettings": {"edit": true, "max": 2, "min": 1}, "completed": true, "url": "https://something.com/pic.png", "StartedAt": "2021-04-01T06:31:41.786Z"}