CSV到JSON的嵌套记录转换

时间:2018-10-05 09:34:38

标签: python json csv

我正在尝试将csv文件中可用的记录转换为JSON格式,以便REST Webservice可以使用它。

示例输入文件:

 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

预期输出:

{ "gfsAuthData": [
        {
            "Id" : "123545",
            "LineNo" :  1,
            "Amt" : "1000.00",
            "ReceivedDt" : "2019-02-01T00:00:00",
            "FromDt" : "2019-02-01T00:00:00",
            "ToDate" : "2019-02-01T00:00:00"
        },
        {
            "Id" : "123545",
            "LineNo" :  2,
            "Amt" : "2000.00",
            "ReceivedDt" : "2019-02-01T00:00:00",
            "FromDt" : "2019-02-15T00:00:00",
            "ToDate" : "2019-02-15T00:00:00"
        }
    ]
}

我应该对我的代码进行哪些修改以实现输出?

代码:

import json,csv

with open('Test.csv') as f:
    inputfile = csv.DictReader(f)
    for row in inputfile :
        print(json.dumps(row, indent=4))

代码输出

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

1 个答案:

答案 0 :(得分:1)

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(json.loads(j))

data = {'gfsAuthData': output}
print(data)

输出:

{'gfsAuthData': [{'Id': '123545', 'LineNo': '1', 'Amt': '1000.00', 'ReceivedDt': '2019-02-01T00:00:00', 'FromDt': '2019-02-01T00:00:00', 'ToDate': '2019-02-01T00:00:00'}, {'Id': '123545', 'LineNo': '2', 'Amt': '200.00', 'ReceivedDt': '2019-02-01T00:00:00', 'FromDt': '2019-02-01T00:00:00', 'ToDate': '2019-02-01T00:00:00'}]}