如何将文本文件数据格式化为特定的标准JSON

时间:2018-07-11 07:03:32

标签: python json dictionary

我在文本文件(test.txt)中有数据,格式如下

ABCD=123=Durham
EFGH=456=Nottingham
IJKL=789=Peterborough

我想将其转换为如下所示的标准json /字典(项目列表)

{
"data":[
         {
         "name":"ABCD",
         "id":"123",
         "place":"Durham",
         },

         {
         "name":"EFGH",
         "id":"456",
         "place":"Nottingham",
         },

         {
         "name":"IJKL",
         "id":"789",
         "place":"Peterborough",
         },
]
}

我该如何实现?

2 个答案:

答案 0 :(得分:1)

import json
input='''ABCD=123=Durham
EFGH=456=Nottingham
IJKL=789=Peterborough'''
print(json.dumps({'data': [dict(zip(('name', 'id', 'place'), l.split('='))) for l in input.split('\n')]}))

这将输出:

{"data": [{"name": "ABCD", "id": "123", "place": "Durham"}, {"name": "EFGH", "id": "456", "place": "Nottingham"}, {"name": "IJKL", "id": "789", "place": "Peterborough"}]}

答案 1 :(得分:1)

希望有帮助

import os
import json

row_keys = ["name","id","place"]

data_dict = {"data":[]}

with open("test.txt", "r") as infile:
    for line in infile:
        row_values = line.split("=")
        row_values[2] = row_values[2].replace(os.linesep, '')
        row_dict = dict(zip(row_keys, row_values))
        data_dict["data"].append(row_dict)
        # print (data_dict)
        # print (row_dict)
json_output = json.dumps(data_dict, ensure_ascii=False)
print (json_output)