TypeError:{}不可序列化为JSON

时间:2018-09-11 07:15:40

标签: python json google-sheets-api

我正在尝试将python字典字符串写入(附加)到Google表格

下面是我的代码

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
SPREADSHEET_ID = 'XXX'
RANGE_NAME = 'Sheet1!A2:F2'
now = time.strftime('%d-%m-%Y %H:%M')


def main():

    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('sheets', 'v4', http=creds.authorize(Http()))


    request = service.spreadsheets().values().append(spreadsheetId= SPREADSHEET_ID,
                                                 range= RANGE_NAME,
                                                 valueInputOption='USER_ENTERED',
                                                 insertDataOption='INSERT_ROWS',
                                                 body= {now, data2['pagespeed_score'], data2['yslow_score'], Loadedtime, pagesize, data2['page_elements'],})
    response = request.execute()

    print(response)

if __name__ == '__main__':
    main()

但是我遇到一个错误:

"TypeError: {2.1982345581054688, '11-09-2018 13:08', 8.836, 109, 52, 55} is not JSON serializable"

我认为值应该为json格式,但我的值位于python字典中。

2 个答案:

答案 0 :(得分:1)

这里:

 body= {now, data2['pagespeed_score'], data2['yslow_score'], Loadedtime, pagesize, data2['page_elements'],}

您正在传递set,它在JSON中没有任何等效项。您必须检查google sheet API文档中的预期类型(实际上可能是dict)。

答案 1 :(得分:0)

通过如下更改代码来解决它,将值集更改为dict

values = [now, pagespeed, yslow, Loadedtime, pagesize, element]
body = {'values': [values]} 


result = service.spreadsheets().values().append(
    spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
    valueInputOption= 'USER_ENTERED', body=body).execute()