将CSV转换为JSON [英] Converting csv to json

查看:307
本文介绍了将CSV转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将CS​​V文件的多行转换为存储在变量中的单行.稍后将其用作rest API的json的一部分.

I am trying to convert multiple rows of CSV file to single row stored in a variable. That will be used later as a part of json for rest API.

我的csv文件如下:

Key     Value
Key1   Value1
Key2   Value2
Key3   Value3

我需要一个输出字符串,例如:

I need an output string like:

Json= "key1":"Value1","key2":"Value2","key3":"Value3"

截至目前,我已经尝试过:

As of now I have tried this:

如果您在docs python中转到csv,则示例为:

if you go to csv in docs python, the example is:

import csv
with open('file.csv', 'r') as csvfile:
csvReader = csv.reader(csvfile)
for row,column in csvReader:
    Json= '"'+row+'":'+column+'",'
Print json

但是,这并没有给我想要的输出.输出最后有逗号.喜欢

But this is not giving me the desired output. The output has comma in the last. Like

Json= "key1":"Value1","key2":"Value2","key3":"Value3",

推荐答案

使用json

尝试如下

import json

csv_dict = dict()

for row,column in csvReader:
    csv_dict[row] = column

dump_variable = json.dumps(csv_dict)
print(dump_variable)

这篇关于将CSV转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆