首页 > 解决方案 > AttributeError: 'int' 对象在使用 json 和字典时没有属性 'items'

问题描述

我有一个代码,其目的是用没有符号的键替换"$oid","$id"键。$执行此操作的函数需要一个字典并返回一个新字典。我的文件包含几个“行”,这就是我需要进行解析的原因(在代码下方我将发布数据示例):

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:
                tmp.append(key_replacer(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) #because I want a .json format at the end. 

对于以下数据样本,它可以工作(我最初认为错误是由于true或 数值):

{"_id":{"$oid":"5d1dc6ba0d27b66b64575bc5"},"quiz":[],"name":"MyName","startDate":{"$date":"2019-07-08T10:00:00Z"},"service":{"$oid":"5d160dc22549bc51860b2736"},"__v":0}
{"_id":{"$oid":"5d5be8a3221257336792a5ad"},"quiz":[],"name":"YourName","repeatable":true,"alertText":"3","startDate":{"$date":"2019-08-19T10:00:00Z"},"service":{"$oid":"5cf8f93af70b3e01bb970fe6"},"__v":0}

它返回:

{"_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' object has no attribute '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'

标签: pythonjsondictionary

解决方案


"types":["easy","hard"]在您的数据中,您的代码尝试调用key_replacer("easy")"easy"不是 dict

代码:

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"}

推荐阅读