2

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....

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

This was all the cause. json = json.dumps(str_json, ensure_ascii=False) I didn't notice With my lack of awareness and 「print(json)」result was in json format... Thank you for teaching me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.