python从输入文件生成json输出

时间:2015-04-09 21:24:34

标签: python json

我有类似输入的文件:

lin1,line2,line3
lin1,line2,line3
lin1,line2,line4

并且需要使用Python将其转换为JSON。例如,输出应该是这样的:

{
    "localport_starts_from": 1080,
    "config": [
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        },
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        },
        {
            "1": "lin1",
            "2": "line2",
            "3": "line3"
        }
    ]
}

我从未使用json库,所以你能告诉我一个如何制作这个的例子吗?

1 个答案:

答案 0 :(得分:1)

使用csv模块解析输入和json以转储解析。

with open(input_file) as f:
    rows = list(csv.reader(f))

# rows will be a list of lists, where each inner list contains the values formerly separated by commas
# e.g. [["lin1", "line2", "line3"], ...]

# enumerate(row, 1) returns a generator of [(1, "lin1"), (2, "line2")...]
row_dicts = [{str(i): v for i, v in enumerate(row, 1)} for row in rows]

# now gather the rest of your stuff into a dict
# ....

result_dict["config"] = row_dicts

with open(output_file, 'w') as f:
     json.dump(result_dict, f)