如何修复Python在对象类型datetime不是JSON序列化错误

5fjcxozz  于 2023-10-21  发布在  Python
关注(0)|答案(2)|浏览(108)

我使用Twitter的数据挖掘。因此,我从twitter获取值create_at以保存在文件Excel中,然后将文件Excel发送到Google Sheet,但它不能发送它。
它有这样的错误:

response = service.spreadsheets().values().append(
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\discovery.py", line 830, in method
headers, params, query, body = model.request(
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\model.py", line 161, in request
body_value = self.serialize(body_value)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\site- 
packages\googleapiclient\model.py", line 274, in serialize
return json.dumps(body_value)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 231, 
in dumps
return _default_encoder.encode(obj)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in 
encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in 
iterencode
return _iterencode(o, 0)
File "C:\Users\What Name\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in 
default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

或者可能是这个代码的问题?

xlApp = win32.Dispatch('Excel.Application')
wb = xlApp.Workbooks.Open(r"F:\work\feen\WU\twitter.xlsx")
ws = wb.WorkSheets('Sheet1')
rngData = ws.Range('A1').CurrentRegion()

gsheet_id = 'sheet_id'
CLIENT_SECRET_FILE = 'credentials2.json'
API_SERVICE_NAME = 'sheets'
API_VERSION = 'v4'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

service = Create_Service(CLIENT_SECRET_FILE,API_SERVICE_NAME,API_VERSION,SCOPES)
response = service.spreadsheets().values().append(
  spreadsheetId=gsheet_id,
  valueInputOption='RAW',
  range='data1!A1',
   body=dict(
      majorDimension='ROWS',
      values=rngData
  )
).execute()

wb.Close(r"F:\work\feen\WU\twitter.xlsx")
qv7cva1a

qv7cva1a1#

回答:

  • 为了修复Object of type datetime is not JSON serializable错误,您需要将对象中datetime对象的所有示例转换为string。*
  • 然而,您的代码中还有其他错误,这意味着仅凭此无法运行您的程序。

datetime对象转换为string对象:

在python中,您可以使用json.dumps()将JSON数据转换为字符串,默认转换为字符串。
你可以通过在service.spreadsheets().values().append()调用之前添加这一行来做到这一点:

//rngData at this point has already been assigned
rngData = json.dumps(rngData, indent = 4, sort_keys = True, default = str)

NB:这本身不会修复您的代码!

其他事项:

在调用Google Sheets API时,以服务器期望接收这些请求的方式发出请求非常重要。也就是说,* 重要的是要遵循文档进行请求。*
我在一台Linux机器上,所以我不能测试win32.Dispatch().Workbooks.Open().Worksheets().Range().CurrentRegion()的输出格式,但是如果Worksheet.Range property of Excel上的Microsoft文档可以参考的话,我可以安全地假设它的输出不是spreadsheets.values.append方法所要求的格式:

array(ListValue格式):

已读取或要写入的数据。这是一个数组的数组,外部数组表示所有数据,每个内部数组表示一个主维度。内部数组中的每一项对应一个单元格。
对于输出,将不包括空的尾随行和列。
对于输入,支持的值类型包括:bool、string和double。将跳过这些值。若要将单元格设置为空值,请将字符串值设置为空字符串。
我不能100%确定输出是否相同,但为了尝试和模拟您正在尝试的内容,我使用python包xlrd从您提供的Excel文件中获取值,如下所示:

workbook = xlrd.open_workbook("twitter.xlsx")
sheet = workbook.sheet_by_index(0)
data = [sheet.row_values(rowx) for rowx in range(sheet.nrows)]

而且,就像你在评论中提供的截图一样(见下文):

我也有同样的React。向上滚动,错误是由于错误的请求:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/XXXXX/values/Sheet1%21A1:append?alt=json&valueInputOption=RAW returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue)..."

具体地说是Invalid value at 'data.values'。您需要遵守Google Sheets API request specification for this method

参考资料:

iszxjhcz

iszxjhcz2#

我正在使用Pydantic,在尝试使用model_dump()时遇到此错误。

TypeError: Object of type datetime is not JSON serializable

解决方案是使用model_dump_json()创建一个JSON字符串,然后使用json库创建一个JSON对象:

import json

json.loads(flashcard.model_dump_json())

相关问题