您好,我是使用python将csv转换为Json的新手。 我试图将csv文件转换为json格式,并在函数调用中返回响应,但得到的是斜杠字符
当我使用记事本打开CSV文件时,数据就是这样显示的
"Sno ","Name","Age ","City"
"1","Alex","27","Newyork"
"2","Smith","25","Los angeles"
"3","austin","26","Calfornia
预期输出:
[
{
"Sno ": "1",
"Name": "Alex",
"Age ": "27",
"City": "Newyork"
},
{
"Sno ": "2",
"Name": "Smith",
"Age ": "25",
"City": "Los angeles"
},
{
"Sno ": "3",
"Name": "austin",
"Age ": "26",
"City": "Calfornia"
}
]
Python代码:
def refresh():
# reading the header from the csv file in an array
with open(r"C:\Users\prasanna.kommuri\example_flask_application\target_py_files\data_file.csv", "r") as f:
reader = csv.reader(f)
csv_header_row = next(reader)
#Reading the content from the csv file
json_data = [json.dumps(d) for d in csv.DictReader(open(r"C:\Users\prasanna.kommuri\example_flask_application\target_py_files\data_file.csv", 'r'), fieldnames=csv_header_row, quotechar='"', delimiter=',',
quoting=csv.QUOTE_ALL, skipinitialspace=True)]
return jsonify(json_data)
实际输出:
[
"{\"Sno \": \"Sno \", \"Name\": \"Name\", \"Age \": \"Age \", \"City\": \"City\"}",
"{\"Sno \": \"1\", \"Name\": \"Alex\", \"Age \": \"27\", \"City\": \"Newyork\"}",
"{\"Sno \": \"2\", \"Name\": \"Smith\", \"Age \": \"25\", \"City\": \"Los angeles\"}",
"{\"Sno \": \"3\", \"Name\": \"austin\", \"Age \": \"26\", \"City\": \"Calfornia\"}"
]
有人能帮我解决哪里出了问题吗?或者任何建议/回答都会有帮助 先谢谢你
请检查这个
输出:
印刷品
或输出到文件
免责声明这并不是解释代码失败的原因,而是提供了一个使用
pandas
的替代解决方案,正如您提到的,您也乐于接受新的解决方案简而言之,假设您有一个指向名为
path_to_csv
的.csv文件的路径,它是一个1行程序:相关问题 更多 >
编程相关推荐