0

i'm having issues on convert list of objects in JSON, i tried with the following:

json.dumps(list)

but i get the following error:

{
  "errorMessage": "Object of type Person is not JSON serializable",
  "errorType": "TypeError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 29, in lambda_handler\n    return json.dumps(list)\n",
    "  File \"/var/lang/lib/python3.8/json/__init__.py\", line 231, in dumps\n    return _default_encoder.encode(obj)\n",
    "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 199, in encode\n    chunks = self.iterencode(o, _one_shot=True)\n",
    "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 257, in iterencode\n    return _iterencode(o, 0)\n",
    "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 179, in default\n    raise TypeError(f'Object of type {o.__class__.__name__} '\n"
  ]
}

i have create a list of objects like the following:

list = []
list.append(Person("a","b","c"))
list.append(Person("d","e","f"))

this is my Person class:

class Person:
    def __init__(self, Title, Link,Snippet):
        self.tite = Title
        self.link = Link
        self.link = Snippet

i would like to export my list of objects in JSON, how can i do that?

Thank you in advacne

  • 1
    Maybe this will be enough for you: https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable – Maciek Apr 29 '20 at 13:26
  • Hello @Maciek i had a look, it show how to Converter an object to a JSON, not a list of Objects to a single JSON. – the gamer x Apr 29 '20 at 13:54

1 Answers1

0

I did it with the following code:

listDict = [x.__dict__ for x in list]
    return json.dumps(listDict)