[英]How do i convert a csv file to a json file for python when csv file is json structured?
大家好 ,
我的一位同事收集了一些Twitter数据(名称,关注者等)。 他使用MongoDB并向我发送了csv-export。 典型的“ pandas.read_csv()..”不起作用。
csv文件的结构如下:
{ “ _id ”:{“ $ oid”:“ 5cf683d18eb9ad12c84f6417”},“ ID”:“ 14400049”,“名称”:“劳拉
这是我的代码:
import csv
import json
csvFilePath = 'xxx'
jsonFilePath = 'yyy'
# read the csv and add the data to a dictionary..
data = {}
with open(csvFilePath, encoding="utf8") as csvFile:
csvReader = csv.DictReader(csvFile)
for rows in csvReader:
id = rows["_id"]
data[id] = rows
# create new json file and write data on it
with open(jsonFilePath, 'w') as jsonFile:
# make it more readeble and prette
jsonFile.write(json.dumps(data, indent=4))
我收到一个关键错误,这意味着循环不获取行[“ _id”]
有人可以帮助我吗? 也欢迎其他解决方案。 我的目标是将数据加载到Jupyter笔记本中。
非常感谢你们。
import pandas as pd
csvFilePath = 'xxx'
jsonFilePath = 'yyy'
csv = pd.read_csv(csvFilePath)
json = csv.to_json()
with open(jsonFilePath, 'w') as jsonFile:
jsonFile.write(json)
我想熊猫包可以帮助您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.