首页 > 解决方案 > AttributeError: 'dict' 对象在将 json 字符串转换为 Python 对象时没有属性

问题描述

我是 Python 新手,正在学习 Python。我有一个要求,我需要将 Python 对象转换为 Json 字符串,并将 Json 字符串转换为 Python 对象,就像我们在 Java 中的 Jackson 中所做的那样。我能够转换为 Json 字符串,但在从 json 字符串转换为 Python 对象时,出现以下错误。

AttributeError:“dict”对象没有属性“firstName”

我在下面提供代码详细信息。

员工对象为

导入json

class Employee:

    def __init__(self):
        self._firstName = None
        self._lastName = None
        self._country = None

    @property
    def firstName(self):
        return self._firstName

    @firstName.setter
    def firstName(self, fName):
        self._firstName = fName

    @property
    def lastName(self):
        return self._lastName

    @lastName.setter
    def lastName(self, lName):
        self._lastName = lName

    @property
    def country(self):
        return self._country

    @country.setter
    def country(self, contryObj):
        self._country = contryObj

    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=True, indent=4)

    def toEmployee(self, jsonString):
        return json.loads(jsonString)

国家对象为

class Country:
    def __init__(self):
        self._countryName = None
        self._countryCode = None

    @property
    def countryName(self):
        return self._countryName

    @countryName.setter
    def countryName(self, cName):
        self._countryName = cName

    @property
    def countryCode(self):
        return self._countryCode

    @countryCode.setter
    def countryCode(self, cCode):
        self._countryCode = cCode

我的测试程序如下。

from toFromJson.Employee import Employee
from toFromJson.Country import Country


def checkEmp():
    emp = Employee()
    emp._firstName = "DD"
    emp._lastName = "Mishra"
    country = Country()
    country.countryCode = "12345"
    country.countryName = "India"
    emp.country = country

    print("Emp in toString format : ", emp.__dict__)
    print("--------------------- IN JSON -----------------")
    print(emp.toJSON())

    jsonString = '{ "_country": { "_countryCode": "7896", "_countryName": "India" }, "_firstName": "John", "_lastName": "Abrham" }'

    emp1 = emp.toEmployee(jsonString)
    print("Employee Name : ", emp1.firstName())
    print("Conveted object : ", emp1.__dict__)


if __name__ == "__main__":
    checkEmp()

上面的代码有什么问题?请帮我解决这个问题。此外,我有几个问题。

  1. Python 中是否有任何框架,就像 Java 中的 Jackson 来回转换?
  2. 如何实现像 @PropertyOrder("firstName","lastName","Country" ...etc) 就像 java 中的 Jackson 在 python 中等效?

在发布这个问题之前,我还浏览了以下 stackoverflow 链接How to make a class JSON serializable

标签: pythonjson

解决方案


您必须为json.loadsand定义钩子json.dumps

import json

class Employee:
    def __init__(self, firstName=None, lastName=None, country=None):
        self.firstName = firstName
        self.lastName = lastName
        self.country = country

class Country:
    def __init__(self, countryName=None, countryCode=None):
        self.countryName = countryName
        self.countryCode = countryCode

def to_json(obj):
    if isinstance(obj, Employee):
        return {
            'firstName': obj.firstName,
            'lastName': obj.lastName,
            'country': obj.country,
        }
    if isinstance(obj, Country):
        return {
            'countryName': obj.countryName,
            'countryCode': obj.countryCode,
        }
    raise TypeError

def from_json(obj):
    if 'firstName' in obj:
        return Employee(**obj)
    if 'countryName' in obj:
        return Country(**obj)
    return obj

def check_emp():
    emp = Employee("DD", "Mishra", Country("India", "12345"))
    json_string = json.dumps(emp, default=to_json, sort_keys=True, indent=4)
    print(json_string)
    emp1 = json.loads(k, object_hook=from_json)
    print("Employee Name : ", emp1.firstName)

if __name__ == "__main__":
    check_emp()

推荐阅读