我正在嘗試分塊讀取 .csv 檔案,并將這些塊轉換為 JSON。問題是,csv 有一列是 json 物件串列(replies在這種情況下):
_id,title,description,count,replies
859f41bd,thr,hrt,5,[]
2816b949,fasd,asdf,2,[{'id': '1e8djah', 'description': 'hey'}]
當我做
for chunk in pd.read_csv(FILE_NAME, chunksize=BATCH_SIZE):
chunk_to_json = pd.DataFrame.to_json(chunk, orient='records')
chunk_to_json 將回復串列作為字串而不是串列:
"replies":"[{'id': '1e8djah', 'description': 'hey'}]"
雖然我看到列型別是object當我做的時候dtypes。并且這樣做會chunk['replies'].apply(lambda x: json.loads(x))回傳錯誤json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)。我希望輸出是:
"replies": [{'id': '1e8djah', 'description': 'hey'}]
是否可以輕松決議這個?我還可以選擇修改將資料放入 .csv 的方式。我使用pandas'to_json把replies里面的csv,所以雙引號要求問題似乎很奇怪。
uj5u.com熱心網友回復:
單引號不是有效的 JSON。您可以簡單地用雙引號替換單引號:
import json
input_string = "[{'id': '1e8djah', 'description': 'hey'}]"
input_string = input_string.replace("\'", "\"")
result = json.loads(input_string)
print(result)
輸出:
[{'id': '1e8djah', 'description': 'hey'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/402570.html
標籤:
下一篇:向Pandas資料庫添加一行
