使用python

时间:2019-12-03 02:19:03

标签: json sql-server python-3.x

我正在尝试使用python将数据从SQL Server数据库转换为JSON格式。我遇到一些错误:

  

引发TypeError(f'类型为{o。 class 的对象。名称}''
   TypeError:Row类型的对象不可JSON序列化

这是我的代码:

    import pyodbc
    import json


    conn = pyodbc.connect('Driver={SQL Server};'
                          'Server=localhost;'
                          'Database=testDb;'
                          'Trusted_Connection=yes;')

    cursor = conn.cursor()
    qa = cursor.execute('select * from dbo.sample where id = 1 FOR JSON PATH').fetchall()

    for row in qa:
         test = json.dumps(qa)
         print (test)

有人可以纠正我我的代码在做什么错吗?

1 个答案:

答案 0 :(得分:0)

您需要将Row对象转换为列表,这意味着dumps(row)不是dumps(qa)对吗?

for row in qa:
     test = json.dumps([x for x in row])
     print (test)