Treesa George
Treesa George

Reputation: 31

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" i.e 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()

Upvotes: 1

Views: 5793

Answers (1)

ysb
ysb

Reputation: 11

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

Upvotes: 1

Related Questions