简体   繁体   中英

How to fix this error please - TypeError: Object of type bytes is not JSON serializable

In my case the JSON file which I need to insert into database is already stored in variable named "data" ie data = res.read() .

I need to insert that "data" into the database directly where my database name called Rest and table called bms . It is getting connected to database. But I am getting the below error. I need help please

Traceback (most recent call last): File "C:\Users\trees\RESTAPI_Python_Code\Test2.py", line 70, in cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data))) File "C:\Python310\lib\json_init.py", line 231, in dumps return default_encoder.encode(obj) File "C:\Python310\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, one_shot=True) File "C:\Python310\lib\json\encoder.py", line 257, in iterencode return iterencode(o, 0) File "C:\Python310\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type bytes is not JSON serializable

My code is below

conn = http.client.HTTPSConnection("120.157.117.168:8443")
payload = ''
headers = {
  'Authorization': f'Bearer {bearer_token}'
}
conn.request("GET", "/api/watches/AHU1%20Control", payload, headers)
#conn.request("GET", "/watches/AHU1%20Control", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))


cnxn = pyodbc.connect("Driver={SQL Server};"
                      "Server=DESKTOP-9KT0GQV;"
                      "Database=Rest;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()

cursor.execute(('INSERT INTO dbo.bms([Value],[Unit],[WatchName])'),(json.dumps(data)))

for row in cursor:
    print(row)

cursor.close()
cnxn.close()

Your object is a bytes object. You need to decode it first (as you did in the print) before drtying to serialize (dumps) it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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