嵌套对象的Python JSON序列化

时间:2018-03-19 07:24:19

标签: python json

我有数据库记录列表,我想将此作为JSON返回给客户端。 记录是Employee对象的类型,应根据工资进行分组。

我已完成对此记录的分组。但我无法生成首选的JSON格式。

" SalaryEmployeeList" object不是JSON可序列化的。

这里的问题是"薪水"和" employee_list"标签丢失。

Python对象:

class Employee:
    def __init__(self, id, name, salary):
        self.id = id
        self.name = name
        self.salary = salary        

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

    def __repr__(self):
        self.toJson()

class SalaryEmployeeList:
    def __init__(self, salary, employee_list):
        self.salary = salary
        self.employee_list = employee_list

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

    def __repr__(self):
        self.toJson()

1 Abi 5000  
2 Bal 6000
3 Con 8000
4 Den 5000
5 Eon 6000
6 Fun 8000
7 Gop 5000
8 Han 6000
9 Iyo 8000
10 John 5000
11 Kami 6000

必需的JSON格式

{
    {
      "salary": 5000,
      "employee_list": [
        {
          "name": "Abi",
          "id": 1          
        },
        {
          "name": "Den",
          "id": 4
        },
        {
          "name": "Gop",
          "id": 7
        },
        {
          "name": "John",
          "id": 10
        }
      ]
    },
    {
      "salary": 6000,
      "employee_list": [
        {
          "name": "Bal",
          "id": 2          
        },
        {
          "name": "Eon",
          "id": 5
        },
        {
          "name": "Han",
          "id": 8
        },
        {
          "name": "Kami",
          "id": 11
        }
      ]
    },
    {
      "salary": 8000,
      "employee_list": [
        {
          "name": "Con",
          "id": 3          
        },
        {
          "name": "Fun",
          "id": 6
        },
        {
          "name": "Iyo",
          "id": 9
        }
      ]
    }  
}

1 个答案:

答案 0 :(得分:0)

如前所述,您需要实现自己的序列化逻辑。此外,我希望以下代码有所帮助:

class Employee:
    def __init__(self, id, name, salary):
        self.id = id
        self.name = name
        self.salary = salary

    def toJson(self):
        return json.dumps({'name': self.name, 'salary': self.salary}, sort_keys=True, indent=4)

    def __repr__(self):
        return self.toJson()


class SalaryEmployeeList:
    def __init__(self, salary, employee_list):
        self.salary = salary
        self.employee_list = employee_list

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

    def __repr__(self):
        return self.toJson()


if __name__ == '__main__':
    a = Employee(1, 'alice', 1000)
    b = Employee(2, 'bob', 2000)
    c = Employee(3, 'carl', 3000)
    employee_list = SalaryEmployeeList(0, [a, b, c])
    json_dictionary = json.loads(employee_list.toJson()) # dictionary loaded from JSON string