Plaid API交易数据JSON字典读写及序列化错误排查求助
Plaid API交易数据JSON读写问题解决记录
遇到的问题
- 读取错误:最初读取存储交易数据的txt文件时,使用以下代码:
with open('./testing/txns.txt', 'r') as f: txns = f.read() txns = txns.replace('"', '\"') # 尝试处理单引号问题
触发json.decoder.JSONDecodeError,原因是文件中包含None、datetime.date(2020, 12, 23)这类Python特有的值格式,不符合JSON标准规范。
- 写入错误:改用直接序列化Plaid API返回数据的方式写入:
response = client.transactions_get(request) with open('txns.txt', 'w') as f: f.write(json.dumps(response.to_dict()))
触发TypeError: Object of type date is not JSON serializable,因为datetime.date类型不属于JSON可序列化的原生类型。
最终解决方案
在json.dumps()中添加default=str参数,将所有无法被JSON序列化的对象(比如date、None)自动转换为字符串形式:
response = client.transactions_get(request) with open('txns.txt', 'w') as f: f.write(json.dumps(response.to_dict(), default=str))
此时写入的文件是标准JSON格式,读取时直接用json.load()即可,无需手动替换引号:
with open('./testing/txns.txt', 'r') as f: txns = json.load(f)
内容的提问来源于stack exchange,提问作者J Smooth
相关产品推荐
相关产品推荐

