如何将CSV转换为JSON? [英] How to convert CSV to JSON?
本文介绍了如何将CSV转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个CSV文件,其标题为Key,数据为Value.我的目标是将CSV文件转换为Json,然后上传到数据库中并输出我上传的数据.我已成功将CSV转换为Json,但是我的输出出现了问题.
I have a CSV file with the header as Key and the data as the Value. My goal is to convert the CSV file into Json to upload into a database and output the data I uploaded. I have successfully converted the CSV into Json,but I am having trouble with my output.
我目前拥有的
import csv
import json
import pandas as pd
csvfile = open ('so-emissions-by-world-region-in-million-tonnes.csv','r')
reader = csv.DictReader(csvfile)
result = []
for row in reader:
result.append(row)
result = json.dumps(result)
result = json.loads(result)
keys = ('Entity' ,'Year','SO2 emissions- Clio Infra')
print(result)
CSV数据:
[{'502 emissions- Clio Infra': '0', 'Entity': 'Africa', 'Year': '1860 '},
{'502 emissions- Clio Infra': '0', 'Entity': 'Africa', 'Year': '1870'},
{'502 emissions- Clio Infra': '0.059', 'Entity': 'Africa', 'Year': '1880'},
{'502 emissions- Clio Infra': '0.065', 'Entity': 'Africa', 'Year': '1890'},
{'502 emissions- Clio Infra': '0.071', 'Entity': 'Africa', 'Year': ' 1900'},
{'502 emissions- Clio Infra': '0.146', 'Entity': 'Africa', 'Year': '1910'},
{'502 emissions- Clio Infra': '0.372', 'Entity': 'Africa', 'Year': '1920'},
{'502 emissions- Clio Infra': '0.41', 'Entity': 'Africa', 'Year': ' 1930'},
{'502 emissions- Clio Infra': '0.56 ', 'Entity': 'Africa', 'Year ': '1940'}]
正确的输出:
'First Key'
Value 1
Value 2
Value 3
...
'Second Key'
Value 1
Value 2
Value 3
...
'Third Key'
Value 1
Value 2
Value 3
...
推荐答案
您可以使用csv.DictReader
读取CSV,然后使用json.dumps
序列化其输出.
You can use the csv.DictReader
to read your CSV and then serialise its output with json.dumps
.
import csv
import json
data = []
with open('file.csv') as f:
for row in csv.DictReader(f):
data.append(row)
json_data = json.dumps(data)
这篇关于如何将CSV转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文