sqlalchemy中json_table的用法,给出代码示例
时间: 2024-03-28 18:41:48 浏览: 420
在SQLAlchemy中,`json_table`函数用于从JSON数组中提取数据并返回表格形式。以下是一个简单的代码示例:
```python
from sqlalchemy import create_engine, Column, Integer, String, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import text
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///test.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
data = Column(String)
Base.metadata.create_all(engine)
users = [
{'name': 'Alice', 'age': 25, 'data': '{"hobbies": ["reading", "swimming"], "address": {"city": "Beijing", "street": "Main Street"}}'},
{'name': 'Bob', 'age': 30, 'data': '{"hobbies": ["gaming", "hiking"], "address": {"city": "Shanghai", "street": "Second Street"}}'},
]
for user_data in users:
user = User(name=user_data['name'], age=user_data['age'], data=user_data['data'])
session.add(user)
session.commit()
# 使用json_table函数从JSON数组中提取数据
stmt = text("""
SELECT
u.id,
u.name,
h.hobby,
a.city,
a.street
FROM
users AS u,
json_table(u.data, '$.hobbies[*]') AS h,
json_table(u.data, '$.address') AS a
WHERE
h.hobby = 'reading' OR h.hobby = 'gaming'
""")
results = session.query(User.id, User.name, func.json_group_array(stmt.columns.hobby), stmt.columns.city, stmt.columns.street).filter(User.id == stmt.columns.id).group_by(User.id).all()
print(results)
```
在这个示例中,我们创建了一个名为`users`的表,其中包含了一个名为`data`的JSON类型字段。我们向表中插入了两个用户的数据。然后,我们使用`json_table`函数从`data`字段中提取了每个用户的兴趣爱好和地址信息,并将查询结果以表格形式返回。最后,我们使用`group_by`函数将结果按用户ID分组。
阅读全文