将对象附加到列表时删除引号

时间:2019-03-06 09:22:09

标签: python

我正在从csv读取数据,我的任务是将csv数据中的几个字段转换为JSON对象,然后最终将这些JSON对象打印为列表。

csv数据示例:

"Station","Longitude","Latitude","Ubication","District Name","Neighborhood Name"
"Barcelona - Ciutadella","2.1874","41.3864","Parc de la Ciutadella","Ciutat Vella","Sant Pere, Santa Caterina i la Ribera"
"Barcelona - Eixample","2.1538","41.3853","Av. Roma - c/ Comte Urgell","Eixample","la Nova Esquerra de l'Eixample"
"Barcelona - Gràcia","2.1534","41.3987","Plaça Gal·la Placídia (Via Augusta - Travessera de Gràcia)","Gracia","la Vila de Gracia"

输出:

['{"Station": "Barcelona - Ciutadella", "District Name": "Ciutat Vella"}', '{"Station": "Barcelona - Eixample", "District Name": "Eixample"}', '{"Station": "Barcelona - Gr\\u00e0cia", "District Name": "Gracia"}', '{"Station": "Barcelona - Palau Reial", "District Name": "Les Corts"}', '{"Station": "Barcelona - Poblenou", "District Name": "Sant Marti"}', '{"Station": "Barcelona - Sants", "District Name": "Sants-Montjuic"}', '{"Station": "Barcelona - Vall Hebron", "District Name": "Horta-Guinardo"}', '{"Station": "Barcelona - Vallvidrera, el Tibidabo i les Planes", "District Name": "Sarri\\u00e0-Sant Gervasi"}']

预期输出:

[...,{"Station":"Barcelona - Vallvidrera, El Tibidabo I Les Planes","District Name":"Sarri\u00e0-Sant Gervasi"}, {"Station: ..., "District Name":"...}, ...]

我面临的问题是如何在打印对象列表时删除引号。

代码:

with open('air_stations_Nov2017.csv', mode='r', encoding='utf=8') as file:
    csv_file = csv.DictReader(file, delimiter=",")
    json_data = []
    for item in csv_file:
        json_data.append(json.dumps({'Station':item['Station'],'District Name':item['District Name']}))
    print(json_data)

请为我提供有关如何删除引号和打印数据的建议。 我尝试过print(','.join(json_data)),但这只是连接所有对象并打印它们而没有列表。

希望你们遇到我的问题。

1 个答案:

答案 0 :(得分:0)

在将dict添加到json_data列表中时不执行JSON转储。 首先填写列表,然后执行json转储。 我已经更改了您的代码:

Set<Phone> set = new TreeSet<>(Comparator.comparing(Phone::getModel));