Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...