我需要将以下 CSV 数据解析为嵌套的 JSON 字符串。请告知我如何将“ payment_mode”添加为“cashier”的嵌套值。我尝试了一些方法,例如创建另一个orderedDict并将其附加到子集列表中,但这并没有按预期工作。将不胜感激任何帮助。
CSV 数据:
Contract_no,sales_date,store_sales_amount,cashier_counter,discount_amount,before_tax_amount,tax_amount,cashier_amount,product,dine_in,take_away,mode,amount
CS,2020-04-12,18.50,C1,0,18.50,0,18.50,18.50,0,0,CASH,1068.50
预期的 JSON 格式:
{
"contract_no": "CS",
"sales_date": "2020-04-06",
"store_sales_amount": "822.17",
"cashier": [
{
"cashier_counter": "C1",
"discount_amount": "15",
"before_tax_amount": "13.15",
"tax_amount": "219.13",
"cashier_amount": "232.28",
"product":"100.12",
"dine_in":"116.02",
"take_away":"16.14",
"payment_mode": [
{
"mode": "CASH",
"amount": "112.46"
}
]
},
]
}
电流输出:
{
"contract_no": "CS",
"sales_date": "2020-04-12",
"store_sales_amount": "18.50",
"cashier": [
{
"cashier_counter": "C1",
"discount_amount": "0",
"before_tax_amount": "18.50",
"tax_amount": "0",
"cashier_amount": "18.50",
"product": "18.50",
"dine_in": "0",
"take_away": "0",
"mode": "CASH",
"cash_amount": "18.50"
}
]
}
代码
import pandas as pd
from itertools import groupby
from collections import OrderedDict
import json
#read csv into dataframe
df = pd.read_csv('sales2.csv', dtype={
#level1
"Contract_no" : str,
"sales_date" : str,
"store_sales_amount" : str,
#level2 cashier
"cashier_counter" : str,
"discount_amount" : str,
"before_tax_amount" : str,
"tax_amount" : str,
"cashier_amount" : str,
"product" : str,
"dine_in" : str,
"take_away" : str,
#level3 payment_mode
"mode" : str,
"cash_amount" : str
})
POPMUISE
相关分类