title: Python JSON serialization for nested object
body: <p>I have list of database records and I want to return this as JSON to the client.
  The records are type of Employee object and should be grouped based on salary.</p>
  
  <p>I have completed grouping this records. But I am not able to generate the preferred JSON format.</p>
  
  <p>"SalaryEmployeeList" object is not JSON serializable.</p>
  
  <p>Here the problem is "salary" and "employee_list" tag is missing.</p>
  
  <p><strong>Python Objects:</strong></p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>Required JSON format</strong></p>
  
  <pre><code>{
      {
        "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
          }
        ]
      }  
  }
  </code></pre>