Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - How to convert CSV to 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.

What I currently have

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 Data:

[{'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'}]

This is the output of result

Correct output:

'First Key'
Value 1
Value 2
Value 3
...
'Second Key'
Value 1
Value 2
Value 3
...
'Third Key'
Value 1
Value 2
Value 3
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...