使用您的数据和PSL
json
给我:
TypeError: Object of type 'int64' is not JSON serializable
这只意味着一些numpy对象存在于嵌套结构中,并且没有
encode
方法将其转换为JSON序列化。
当对象本身缺少字符串转换时,强制encode使用字符串转换足以使代码正常工作:
import io
d = io.StringIO("datasource,datasource_cnt,category,category_cnt,subcategory,subcategory_cnt\nBureau of Labor Statistics,44,Employment and wages,44,Employment and wages,44")
df=pd.read_csv(d)
abc=list(split_df(df))
import json
json.dumps(abc, default=str)
它返回一个有效的JSON(但带有
int
转化为
str
):
'[{"vendor_name": "Bureau of Labor Statistics", "count": "44", "categories": [{"name": "Employment and wages", "count": "44", "subCategories": [{"count": "44", "name": "Employment and wages"}]}]}]'
如果不适合您的需要,请使用专用的
Encoder
import numpy as np
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.int64):
return int(obj)
return json.JSONEncoder.default(self, obj)
json.dumps(abc, cls=MyEncoder)
这将返回请求的JSON:
'[{"vendor_name": "Bureau of Labor Statistics", "count": 44, "categories": [{"name": "Employment and wages", "count": 44, "subCategories": [{"count": 44, "name": "Employment and wages"}]}]}]'
另一种选择是在编码之前直接转换数据:
def split_category(df_vendor):
for (category, count), df_category in df_vendor.groupby(
["category", "category_cnt"]
):
yield {
"name": category,
"count": int(count), # Cast here before encoding
"subCategories": list(split_subcategory(df_category)),
}