Ask Your Question
1

How can I use sqlalchemy to merge JSON within a column of mysql?

asked 2022-09-27 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-28 04:00:00 +0000

nofretete gravatar image

You can use the func.json_merge function from SQLAlchemy to merge JSON values within a column in MySQL. Here's an example:

from sqlalchemy import create_engine, Column, Integer, JSON, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://user:password@host/dbname')
Session = sessionmaker(bind=engine)

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'mytable'
    id = Column(Integer, primary_key=True)
    json_data = Column(JSON)

# Create a session
session = Session()

# Merge two JSON values within a column
result = session.query(func.json_merge(MyTable.json_data, '{"key": "value"}')).filter(MyTable.id == 1).one()

# Commit the changes
session.commit()

In this example, json_data is a column in the mytable table that contains JSON data. The func.json_merge function is used to merge the existing JSON data with the new data ('{"key": "value"}') for the row with id equal to 1. The one() method is used to retrieve the result as a single row. Finally, the changes are committed to the database using session.commit().

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-27 11:00:00 +0000

Seen: 15 times

Last updated: Nov 28 '21