0

I have a class called Employee and there is list which contains instance of Employee. I tried the below approach:

class Employee:
    empId
    empName

    def __init__(self, empId, empName):
            self.empId = empId
            self.empName = empName

    class Test:
        def convertJson(self):
            employees=[]
            emp1 = Employee(101,'John')
            employees.append(emp1)
            emp2 = Employee(102,'Smith')
            employees.append(emp2)
            employeeList = json.dumps(employees.__dict__) # Need to convert employees into json

It throws exception, list has no attribute 'dict

Saurabh
  • 867
  • 3
  • 13
  • 28
  • Is the `class Test` defined inside `class Employee`? – C.Nivs May 01 '19 at 17:23
  • you're trying to access the attribute `__dict__` in employees, but since employees is a list, that fails. perhaps you mean to use `json.dumps(employees)`? – codelessbugging May 01 '19 at 17:23
  • What is the point of `class Test`? In any case, `list` objects do not have a `__dict__` attribute, but they are directly JSON serializable to JSON arrays. The problem is, custom classes are not. There is a duplicate for that though... – juanpa.arrivillaga May 01 '19 at 17:24
  • @C.Nivs both classes are separate to each other. `Test` class is not defined inside `Employee` class – Saurabh May 01 '19 at 18:03
  • @CodelessBugging I tried that approach also it throws exception like `emp1 and emp2 is not json` . Can you please suggest a approach – Saurabh May 01 '19 at 18:06
  • @juanpa.arrivillaga 's comment addresses that issue. look at the duplicate question – codelessbugging May 02 '19 at 05:40

0 Answers0