nayuta shiba
nayuta shiba

Reputation: 425

How to save json type with flask-sqlalchemy?

I am currently developing an app using Flask + Vue. I use flask-sqlalchemy for ORM.

When saving json to JSON type to MySQL, the action registers the data as a string versus a JSON object.

Is it possible to save the value in JSON?

Sample code:

from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

db = SQLAlchemy()
marsh = Marshmallow()
from database import db, marsh
from sqlalchemy.dialects.mysql import insert

class UserInfo(db.Model):
    __tablename__ = 'user_info'

    user_id = db.Column(db.String, nullable=False, primary_key=True)
    json= db.Column(db.JSON, nullable=True)

    def insert_on_duplicate_key_update(user_id, str_json):
        json = json.dumps(str_json, ensure_ascii=False)
        insert_stmt = insert(UserInfo).values({UserInfo.user_id: user_id
                                               UserInfo.json : json })

        print(json)
        // print {"item1": false} 

        on_conflict_stmt = insert_stmt.on_duplicate_key_update(
            json=insert_stmt.inserted.json)

        db.engine.execute(on_conflict_stmt)

        return insert_stmt

class UserInfoSchema(marsh.ModelSchema):
    class Meta:
        model = UserInfo
        fields = ("user_id", "json")

Registration result:

select * from user_info;

{\"item1\": false}

I want to save in the following state.

{"item1": false}

I am Japanese. Sorry for poor English....

Upvotes: 2

Views: 4654

Answers (1)

c8999c 3f964f64
c8999c 3f964f64

Reputation: 1627

json.dumps is to make json into string

Here you make json into string:

json = json.dumps(str_json, ensure_ascii=False)

dont need. database will accept json. Possible, I use it. Maybe you need json.loads?

Upvotes: 2

Related Questions