如何将CSV转换为JSON?

Ale*_*hen 3 python csv json dictionary

我有一个CSV文件,标题为Key,数据为Value.我的目标是将CSV文件转换为Json以上传到数据库并输出我上传的数据.我已成功将CSV转换为Json,但我的输出有问题.

我现在有什么

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)
Run Code Online (Sandbox Code Playgroud)

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'}]
Run Code Online (Sandbox Code Playgroud)

这是结果的输出

正确输出:

'First Key'
Value 1
Value 2
Value 3
...
'Second Key'
Value 1
Value 2
Value 3
...
'Third Key'
Value 1
Value 2
Value 3
...
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 8

您可以使用它csv.DictReader来读取CSV,然后使用序列化输出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)
Run Code Online (Sandbox Code Playgroud)