我正在创建一个嵌套的 json,并将其存储在一个列表对象中。这是我的代码,它按预期获得了正确的分层 json。
样本数据:
datasource,datasource_cnt,category,category_cnt,subcategory,subcategory_cnt 劳动统计局,44,就业和工资,44,就业和工资,44
import pandas as pd
df=pd.read_csv('queryhive16273.csv')
def split_df(df):
for (vendor, count), df_vendor in df.groupby(["datasource", "datasource_cnt"]):
yield {
"vendor_name": vendor,
"count": count,
"categories": list(split_category(df_vendor))
}
def split_category(df_vendor):
for (category, count), df_category in df_vendor.groupby(
["category", "category_cnt"]
):
yield {
"name": category,
"count": count,
"subCategories": list(split_subcategory(df_category)),
}
def split_subcategory(df_category):
for (subcategory, count), df_subcategory in df_category.groupby(
["subcategory", "subcategory_cnt"]
):
yield {
"count": count,
"name": subcategory,
}
abc=list(split_df(df))
abc 包含如下所示的数据。这是预期的结果。
[{
'count': 44,
'vendor_name': 'Bureau of Labor Statistics',
'categories': [{
'count': 44,
'name': 'Employment and wages',
'subCategories': [{
'count': 44,
'name': 'Employment and wages'
}]
}]
}]
现在我试图将它存储到一个 json 文件中。
with open('your_file2.json', 'w') as f:
for item in abc:
f.write("%s\n" % item)
#f.write(abc)
问题来了。这会以这种方式写入数据(请参阅下文),这不是有效的 json 格式。如果我尝试使用 json 转储,它会给出“json 序列化错误”
你能帮我吗?
{
'count': 44,
'vendor_name': 'Bureau of Labor Statistics',
'categories': [{
'count': 44,
'name': 'Employment and wages',
'subCategories': [{
'count': 44,
'name': 'Employment and wages'
}]
}]
}
预期结果 :
[{
"count": 44,
"vendor_name": "Bureau of Labor Statistics",
"categories": [{
"count": 44,
"name": "Employment and wages",
"subCategories": [{
"count": 44,
"name": "Employment and wages"
}]
}]
}]