PYODBC truncates the response of a SQL Server FOR JSON query

后端 未结 2 1573
失恋的感觉
失恋的感觉 2021-01-19 07:59

I\'m having issues trying to get a SQL Server JSON result set to play nicely with PYODBC. My Python/Flask skills aren\'t the best, so I\'m not entirely sure if this is somet

相关标签:
2条回答
  • 2021-01-19 08:27

    I ran into this same bizarre issue today. The JSON result, which ought to be a single row and column, is cut off at 2033 characters.

    However, the result set is all there, just spread across many rows! You can reconstruct it:

    rows = cursor.fetchall()
    json_result = ''
    json_result = json_result.join([row[0] for row in rows])
    

    Or alternately:

    rows = cursor.fetchall()
    search_results = json.loads(''.join([row[0] for row in rows]))
    

    Switching between ODBC Driver 13 for SQL Server and SQL Server drivers didn't help. I'm on Windows 10, Python 3.7, pyodbc 4.0.26, and SQL Server 2017.

    This seems like a bug.

    0 讨论(0)
  • 2021-01-19 08:32

    Thanks to a combination of the comments above, I have managed to get this working.

    In case anyone else comes across my issue, I'll summarise:

    1. As per @GordThompson's comment, I changed the driver from the old SQL Server to ODBC Driver 13 for SQL Server. There were a couple of tweaks needed in my parameter passing once I had upgraded the driver version, but on the whole this seemed like a wise move

    2. Perhaps more importantly, @FlipperPA's comment suggested I CAST the JSON Object in the SQL Server query to a VARCHAR(MAX).

      SELECT CAST( (SELECT ..... FOR JSON PATH) AS VARCHAR(MAX))

      This returned the full JSON object that was being selected and everything is now working correctly.

    I can only assume there is some issue with pyodbc supporting JSON in SQL Server 2017/Azure?

    0 讨论(0)
提交回复
热议问题