I am creating a nested json and i am storing it in a list object. Here is my code which is getting the proper hierarchical json as intended.
Sample Data:
datasource,datasource_cnt,category,category_cnt,subcategory,subcategory_cnt Bureau of Labor Statistics,44,Employment and wages,44,Employment and wages,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 is containing the data as shown below. This is the intended result.
[{
'count': 44,
'vendor_name': 'Bureau of Labor Statistics',
'categories': [{
'count': 44,
'name': 'Employment and wages',
'subCategories': [{
'count': 44,
'name': 'Employment and wages'
}]
}]
}]
Now I am trying to store it into a json file.
with open('your_file2.json', 'w') as f:
for item in abc:
f.write("%s\n" % item)
#f.write(abc)
Here comes the issue. This writes data in this fashion( refer below) which is not a valid json format. If i try to use json dump, it gives "json serialize error"
Could you please help me out here.
{
'count': 44,
'vendor_name': 'Bureau of Labor Statistics',
'categories': [{
'count': 44,
'name': 'Employment and wages',
'subCategories': [{
'count': 44,
'name': 'Employment and wages'
}]
}]
}
Expected Result :
[{
"count": 44,
"vendor_name": "Bureau of Labor Statistics",
"categories": [{
"count": 44,
"name": "Employment and wages",
"subCategories": [{
"count": 44,
"name": "Employment and wages"
}]
}]
}]
