1 | initial version |
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()
.