CSV到JSON转换组合集属于同一个键

时间:2018-10-08 16:34:08

标签: python json

我正在尝试从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可以具有行号的倍数,并且所有这些记录都应位于单个集中。

所需格式:

{
    "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))

1 个答案:

答案 0 :(得分:1)

您正在考虑数据结构错误。您应该这样使用dict:

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"
        }
    ]}
}