csv与json互转_如何将CSV转换为JSON?

该博客讲述了作者在将CSV文件转换为JSON并上传到数据库的过程中遇到的问题。他们成功将CSV转换为JSON,但在输出结果时遇到了困难。代码示例展示了如何使用csv和json模块读取CSV并转换为JSON格式,但最终输出格式不正确。正确的输出应该是键值对的形式。
摘要由CSDN通过智能技术生成

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

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

...

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值