Astrid
Astrid

Reputation: 31

Using Python Dataclasses to output raw JSON

I am using Python Dataclasses to aid in outputting my SQL Alchemy data models as JSON as outlined here. The problem is one of my class attributes is a string of serialized unstructured JSON data stored in the database and I would like to be able to output that as raw JSON. The problem is I cannot seem to find the correct data type to allow this. I have tried dict, json and object but all of these still result in the JSON field being populated with a delimited string as in the area marked "current output". Is there a way to do this with dataclasses?

class Event(db.Model):
    id: int
    data: ???

    __tablename__ = "data"
    id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
    data = db.Column('data', db.Text, nullable=True)

Current Output:

   {
     "id": 1,
     "data": "{\"data\": \"this is data\"}"
   }

Expected Output:

   {
     "id": 1,
     "data": {"data": "this is data"}
   }

Upvotes: 1

Views: 909

Answers (1)

Astrid
Astrid

Reputation: 31

Solved! For those finding this in the future if you are dead set on converting strings to JSON at this point my answer will not be useful but setting the datatype used by SQL alchemy to JSON resolved the problem as SQL Alchemy handles the string to JSON conversion when loading the object from the DB.

class Event(db.Model):
    id: int
    data: json

    __tablename__ = "data"
    id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
    data = db.Column('data', db.JSON, nullable=True)

Upvotes: 1

Related Questions