简体   繁体   English

使用 SQLAlchemy 查询 SQL 服务器 JSON 列

[英]Query SQL Server JSON columns using SQLAlchemy

I'm looking for a way to replicate the functionality of SQL Server's JSON_VALUE function using a SQLAlchemy query.我正在寻找一种方法来使用 SQLAlchemy 查询复制 SQL 服务器的 JSON_VALUE function 的功能。 I'm using metadata.reflect to define my existing db tables in SQLAlchemy.我正在使用 metadata.reflect 在 SQLAlchemy 中定义我现有的数据库表。

SQL: SQL:

SELECT Id,
JSON_VALUE(BankDataJSON,'$.AccountName')
FROM BankData

SQLAlchemy Model: SQLAlchemy Model:

db = SQLAlchemy()
db.Model.metadata.reflect(db.engine)

class BankData(db.Model):
    __table__ = db.Model.metadata.tables['BankData'] 

Endpoint / Query:端点/查询:

@cust_accts_bp.route('/api/CustomerAccts')
def get_cust_accts():
    custId = request.args.get('custId')

    db = SQLAlchemy(app)
    BankData = models.bank_data.BankData
    BankAccounts = models.bank_accounts.BankAccounts

    qry = db.session.query(BankAccounts.Id, BankAccounts.AccountNumber, BankAccounts.BankName,
                           BankData.AppId, BankData.CustomerId, BankAccounts.Filename, BankData.BankDataJSON) \
                           .filter(
                               and_(BankData.Id == BankAccounts.BankDataId, BankData.CustomerId == custId)
                            )

    engine = app.config['SQLALCHEMY_DATABASE_URI']
    df = pd.read_sql(qry.statement, engine)

    df['BankDataJSON'] = df['BankDataJSON'].apply(json.loads) # convert string representation of JSON
    df['BankDataJSON'] = df['BankDataJSON'].map(lambda x:[x[i] for i in x if i=='AccountName'][0])
    df = df.rename(columns={'BankDataJSON':'BusinessName'})

    response = json.loads(df.to_json(orient="records"))

    return(json.dumps(response))

Using this method, I have to manually serialize the JSON object (BankDataJSON) to a Python dict, and parse it to get the value I want ('AccountName').使用这种方法,我必须手动将 JSON object (BankDataJSON) 序列化为 Python 字典,并解析它以获得我想要的值('AccountName')。 If I were to use SQL Server's JSON_VALUE function, this is all done for you.如果我使用 SQL 服务器的 JSON_VALUE function,这一切都为你完成。

JSON response: JSON 响应:

[
  {
    "Id": 3003,
    "AccountNumber": "111111111",
    "BankName": "Wells Fargo",
    "AppId": 111111,
    "CustomerId": "555555",
    "Filename": "some filename.pdf",
    "BusinessName": "Some BusinessName"
  },
  {
    "Id": 3004,
    "AccountNumber": "22222222",
    "BankName": "Wells Fargo",
    "AppId": 111111,
    "CustomerId": "555555",
    "Filename": "Some filename",
    "BusinessName": "Some Businessname"
  },
]

How can I go about doing this?我怎么能 go 关于这样做? I walso want to be able to replicated SQL Server's CROSS APPLY OPENJSON functionality for working with array of JSON objects in the future.我还希望能够复制 SQL 服务器的 CROSS APPLY OPENJSON 功能,以便在将来使用 JSON 对象数组。 Do I need to define the BankDataJSON column as a JSON type in my model?我是否需要在 model 中将 BankDataJSON 列定义为 JSON 类型? When I do this, I get an error regarding pyodbcs inability to deserialize JSON in the MSSQL dialect当我这样做时,我收到有关 pyodbcs 无法在 MSSQL 方言中反序列化 JSON 的错误

may be you can try to implement the server's function in your query, something like this可能你可以尝试在你的查询中实现服务器的 function ,像这样

from sqlalchemy.sql import func


db = SQLAlchemy(app)
BankData = models.bank_data.BankData

qry = db.session.query(BankData.Id, 
     func.JSON_VALUE(BankData.BankDataJSON,'$.AccountName'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM