0

Can someone help me how to encode python list to JSON to send over the network.

Since this is a custom object I am not able to use json.dumps

The below is the code

 @cherrypy.tools.json_out()
    def display(self):
        with Session(engine) as session:
            statement = select(Hero)
            results = session.exec(statement)
            heros = results.all()
            print(type(heros))            
            print(heros)
            return "heros_json"
print(type(heros)) - <class 'list'>
print(heros) - [Hero(age=None, id=1, name='Deadpond', secret_name='Dive Wilson'), Hero(age=None, id=2, name='Spider-Boy', secret_name='Pedro Parqueador'), Hero(age=48, id=3, name='Rusty-Man', secret_name='Tommy Sharp')]
class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

jeril
  • 1,109
  • 2
  • 17
  • 35

1 Answers1

2

I think you could build json directly from objects.

Example

heros_as_array_json = []

for hero in heros: 
    heros_as_array_json.append(json.dumps(
       {
        "age": hero.age,
        "id":hero.id,
        "name": hero.name,
        "secret_name": hero.secret_name
       }
      )
    )

zzob
  • 993
  • 3
  • 9
  • 19