【发布时间】:2019-08-15 08:36:34
【问题描述】:
我已经编写了一个代码来转换我的 csvfile 是 '|'分隔文件以获取特定的 json 格式。
CSV 文件格式:
comment|address|city|country
crowded|others|others|US
pretty good|others|others|US ....
我也尝试过其他代码,因为我是 python 新手,我被困在两者之间。如果有人帮助我纠正我正在做的错误,那将会很有帮助。
import csv
import json
from collections import OrderedDict
csv_file = 'test.csv'
json_file = csv_file + '.json'
def main(input_file):
csv_rows = []
with open(input_file, 'r') as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
entry = OrderedDict()
for field in title:
entry[field] = row[field]
csv_rows.append(entry)
with open(json_file, 'w') as f:
json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
f.write('\n')
if __name__ == "__main__":
main(csv_file)
我想要下面的json格式
{
"reviewer": {
"city": "",
"country": ""
"address": "Orlando, Florida"
},
但我得到这样的输出:
[
{
"COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"Crowded"|"Others"|"Others"|
},
{
"COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"pretty good"|"Others"|"Others"|
},
【问题讨论】:
-
如何以嵌套的 json 格式获得相同的输出?我正在使用这种格式。[ { "ADDRESS": "Others", "CITY": "Others", "COUNTRY": "Others" } ] 但我想要嵌套 json 格式的输出,例如 { "reviewer": {“城市”:“”,“国家”:“”“地址”:“佛罗里达州奥兰多”}}
标签: python json python-2.7 csv