簡體   English   中英

當csv文件為json結構時,如何將csv文件轉換為python的json文件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM