无法将Json转换为Dataframe:JSON序列化与反序列化类型错误求助
无法将JSON转换为Dataframe的TypeError问题解决
问题与报错
已创建数据并执行转换代码:
Test_data = { 'archived': False, 'archived_at': None, 'associations': None, 'created_at': datetime.datetime(2020, 10, 30, 8, 3, 54, 190000, tzinfo=tzlocal()), 'id': '12345', 'properties': { 'createdate': '[![2020-10-30T08:03:54.190Z][1]][1]', 'email': 'testmail@gmail.com', 'firstname': 'TestFirst', 'lastname': 'TestLast' }, 'properties_with_history': None, 'updated_at': datetime.datetime(2022, 11, 10, 6, 44, 14, 5000, tzinfo=tzlocal()) } data = json.loads(test_data)
触发报错:
TypeError: the JSON object must be str, bytes or bytearray, not SimplePublicObjectWithAssociations
已尝试操作
尝试先序列化再反序列化:
s1 = json.dumps(test_data) d2 = json.loads(s1)
仍报错:
TypeError: Object of type SimplePublicObjectWithAssociations is not JSON serializable
期望输出

解决步骤
- 转换对象为原生字典
Test_data是SimplePublicObjectWithAssociations类型(常见于HubSpot API返回结果),需先调用对象的to_dict()方法转为Python原生字典:
test_data_dict = test_data.to_dict()
- 处理datetime序列化问题
字典中的datetime对象无法直接JSON序列化,需自定义序列化函数:
import json from datetime import datetime def datetime_serializer(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(f"Type {type(obj)} not serializable")
- 生成Dataframe
先序列化字典,再解析后整理数据生成Dataframe:
# 序列化字典 json_str = json.dumps(test_data_dict, default=datetime_serializer) data = json.loads(json_str) # 整理数据,合并顶层字段与properties字段 import pandas as pd df_data = { 'id': data['id'], 'created_at': data['created_at'], 'updated_at': data['updated_at'], **data['properties'] } # 清理createdate字段的冗余格式 df_data['createdate'] = df_data['createdate'].split(']')[0].split('[')[2] # 生成Dataframe df = pd.DataFrame([df_data])
内容的提问来源于stack exchange,提问作者Marcelle de Jager
相关产品推荐
相关产品推荐

