[英]CSV to JSON conversion combining sets belong to same key
我正在嘗試從 csv 文件生成一個 json 請求表。 REST Web 服務需要此請求表。
示例輸入文件:
Id,LineNo,Amt,ReceivedDt,FromDt,ToDate
123545,1,1000.00,2019-02-01T00:00:00,2019-02-01T00:00:00,2019-02-01T00:00:00
123545,2,200.00,2019-02-01T00:00:00,2019-02-01T00:00:00,2019-02-01T00:00:00
123546,1,200.00,2019-02-01T00:00:00,2019-02-01T00:00:00,2019-02-01T00:00:00
文件中有更多記錄遵循上述結構。 一個 Id 可以有多個 Line No,並且所有這些記錄都應該在一個集合中。
所需格式:
{
"consumerData": {
"clientCode": "CLINIC",
"instance": "P",
"userId": ""
},
"gfsauthdata": [
{
"ToDate": "2019-02-01T00:00:00",
"ReceivedDt": "2019-02-01T00:00:00",
"Id": "123545",
"LineNo": "1",
"Amt": "1000.00",
"FromDt": "2019-02-01T00:00:00"
},
{
"ToDate": "2019-02-01T00:00:00",
"ReceivedDt": "2019-02-01T00:00:00",
"Id": "123545",
"LineNo": "2",
"Amt": "200.00",
"FromDt": "2019-02-01T00:00:00"
}
]
},
{
"consumerData": {
"clientCode": "CLINIC",
"instance": "P",
"userId": ""
},
"gfsauthdata":
{
"ToDate": "2019-02-01T00:00:00",
"ReceivedDt": "2019-02-01T00:00:00",
"Id": "123546",
"LineNo": "1",
"Amt": "200.00",
"FromDt": "2019-02-01T00:00:00"
}
}
我無法將不同的記錄分開。 請提出一些將其分開的方法。 我正在使用下面的代碼,它將 csv 傳輸到 json,但所有記錄都是單組的。
代碼 :
import json,csv
with open('Test.csv') as f:
inputfile = csv.DictReader(f)
output = []
for row in inputfile :
#j = json.dumps(row, indent=4)
output.append(row)
data = {
'consumerData': {
'clientCode': 'CLINIC',
'instance': 'P',
'userId': ''
},
'gfsauthdata': output
}
print(json.dumps(data, indent=4))
您正在考慮錯誤的數據結構。 你應該像這樣使用字典:
data[userid] = {
"type": "CLINIC",
"instance": "P",
"gfsauthdata": [
{
"ToDate": "2019-02-01T00:00:00",
"ReceivedDt": "2019-02-01T00:00:00",
"Id": "123545",
"LineNo": "1",
"Amt": "1000.00",
"FromDt": "2019-02-01T00:00:00"
},
{
"ToDate": "2019-02-01T00:00:00",
"ReceivedDt": "2019-02-01T00:00:00",
"Id": "123545",
"LineNo": "2",
"Amt": "200.00",
"FromDt": "2019-02-01T00:00:00"
}
]}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.