[英]How to convert CSV to JSON?
我有一個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)
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
其輸出序列化。
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)
您當前正在打印字典本身的結果,如果您希望以問題中顯示的格式獲得輸出,則需要通過字典打印出每個鍵及其值
for key in keys: #looking through each key
print (key)
for i in results: #going through the results and printing the value of the index with the current key
print (results[i][key])
這應該在控制台中提供預期的輸出,如上所述
如果在數據.to_dict
加載數據,可以嘗試使用.to_dict
。
df = pd.read_csv('so-emissions-by-world-region-in-million-tonnes.csv')
df.T.to_dict().values()
.to_dict()
按列轉換地圖中的數據.to_dict()
對於每個列,您有index-> value)。 通過轉置和使用.to_dict
,這是一個按行的映射(對於每個索引,你有一個map column-> value)。 你不需要密鑰,所以只需要.values()
注意,如果你使用python 3.5,這是一個dict_values
對象,所以你可能想在轉換為json之前使用list()
。
順便說一下,您還可以使用dict(zip(columns, values))
來獲取每行的map column-> value,這樣會更快。 在這種情況下,你根本不需要熊貓。
編輯:如果csv沒有標題,你需要在pd.read_csv()
傳遞它,關鍵字names=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.