使用Python将DataFrame转换为嵌套JSON?

使用Python将DataFrame转换为嵌套JSON?,python,json,sql-server,firebase,dataframe,Python,Json,Sql Server,Firebase,Dataframe,我试图从SQL中提取数据并将其转换为JSON文件 我还尝试了各种网站上提到的其他“技巧”,但没有成功 所以基本上,在下面的陈述之后,我被“卡住”了 j = (df.groupby(['SectionCode']) .apply(lambda x: x[['Barcode', 'BrandCode', 'PurchaseRate', 'SalesRate', 'unit','Item']].to_dict('r')) .reset_index() .rename(co

我试图从SQL中提取数据并将其转换为JSON文件

我还尝试了各种网站上提到的其他“技巧”,但没有成功

所以基本上,在下面的陈述之后,我被“卡住”了

j = (df.groupby(['SectionCode'])
     .apply(lambda x: x[['Barcode', 'BrandCode', 'PurchaseRate', 'SalesRate', 'unit','Item']].to_dict('r'))
     .reset_index()
     .rename(columns={0: 'Products'})
     .to_json(r'D:\DataToFirbaseWithPython\Export_DataFrame.json'))

print(j)
需要这个json格式

"SectionsWithItem": { #Root_Nose_In_Firebase
  "0001": { #SectionCode
    "Products": {
            "018123": { #Barcode
        "Barcode": "018123",
                "BrandCode": "1004",
                "PurchaseRate": 105.0,
                "SalesRate": 125.0,
                "Units": "Piece",
                "name": "Shahi Delux Mouth Freshener"
            },
            "0039217": { #Barcode
        "Barcode": "0039217",
                "BrandCode": "0814",
                "PurchaseRate": 140.0,
                "SalesRate": 160.0,
                "Units": "Piece",
                "name": "Maizban Gota Pan Masala Medium Jar"
            }
        }
    },
    "0002": { #SectionCode
    "Products": {
            "03905": { #Barcode
        "Barcode": "03905",
                "BrandCode": "0189",
                "PurchaseRate": 15.4,
                "SalesRate": 17.0,
                "Units": "Piece",
                "name": "Peek Freans Rio Chocolate Half Roll"
            },
            "0003910": { #Barcode
        "Barcode": "0003910",
                "BrandCode": "0189",
                "PurchaseRate": 110.32,
                "SalesRate": 120.0,
                "Units": "Piece",
                "name": "Peek Freans Gluco Ticky Pack Box"
            }
        }
    }
}
我的数据帧

Barcode,Item,SalesRate,PurchaseRate,unit,BrandCode,SectionCode
0005575,Broom Soft A Quality,100.0,80.0,,2037,0045
0005850,Safa Tomato Paste 800g,340.0,275.0,800g,1004,0009
0005921,Dettol Liquid 1Ltr,800.0,719.99,1Ltr,0475,0045

按条形码分组也应有助于索引,如所需的输出

import pandas as pd
import json

df = pd.read_csv('stac1 - Sheet1.csv', dtype=str) #made dataframe with provided data

j = (df.groupby(['SectionCode', 'Barcode'])
     .apply(lambda x: x[['Barcode', 'BrandCode', 'PurchaseRate', 'SalesRate','unit','Item']].to_dict('r'))
     .reset_index()
     .rename(columns={0: 'Products'})
     .to_json(r'Export_DataFrame.json'))

with open('Export_DataFrame.json') as f:
    data = json.load(f)

print(data)
希望这能帮你找到正确的方向