You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将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

期望输出

期望的Dataframe格式

解决步骤

  1. 转换对象为原生字典
    Test_data是SimplePublicObjectWithAssociations类型(常见于HubSpot API返回结果),需先调用对象的to_dict()方法转为Python原生字典:
test_data_dict = test_data.to_dict()
  1. 处理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")
  1. 生成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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:30:46