我有一個CSV檔案,其中每一行代表一個json物件。我正試圖將其轉換為一個包含json物件陣列的檔案。
我應該先說,我不是一個經驗豐富的 Python 開發者。
CSV 檔案中的示例資料,包含 2 個條目:
{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "開發人員"}, "職業": "開發人員"}.
{"first_name": "Joe", "last_name": "Plumb", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "plumber"}, "plumber"}.
期望的輸出:
[{
"first_name"/span>: "Jason"。
"last_name": "Elwood",
"last_modified": {
"type": "/type/datetime"。
"value": "2008-08-20T17:57:46.368856"
},
"職業": "開發人員"。
},
{
"first_name": "Joe",
"last_name": "Plumb",
"last_modified": {
"type": "/type/datetime"。
"value": "2008-08-20T17:57:46.368856"
},
"職業": "水管工"。
}
下面是一些Python代碼,它近似于我試圖做的事情(為了演示,首先我列印一個本地json格式的字串,然后我從讀取的CSV檔案中列印:
python:
# Python3。
# 讀取CSV檔案為json物件的陣列。
# 初始化字串
test_string = '{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"型別": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "開發人員"}'
print("test_string:"/span>)
print(test_string)
arr = []
arr.append(str(test_string))
#列印原始字串。
print("Array from test_string :"/span>)
print(arr)
arr = []
with open('testData.csv') as f。
for row in f:
arr.append(row)
print(" Array from file:")
print(arr)
下面是輸出結果:
test_string:
{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "開發人員"}, "職業": "開發人員"}
Array from test_string :
['{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"型別": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "開發人員"}']
Array from file:
['"{"first_name"": ""Jason"", ""last_name"": ""Elwood"", ""last_modified"": {""型別"": ""/type/dateetime"", ""value"": ""2008-08-20T17:57:46.368856""}, ""occupation"": ""developer""}"']
a. 硬編碼的字串列印得很好:即一個有效的json格式的字串。
b. 一旦添加到一個陣列中,硬編碼的字串就會被單引號所包圍。
c. 然而,csv匯入的字串被包圍在引號中,所有預先存在的引號都被重復了。
重申一下,我想要一個可以輕松匯入NoSQL資料庫的json物件陣列。
非常感謝任何幫助。如果我可以提供更多的資訊,以幫助描述我現在的情況和期望的結果,請讓我知道。
提前感謝,祝您愉快!
uj5u.com熱心網友回復:
這不是一個CSV檔案。它是一堆行分離的json記錄。你不要試圖把它當作CSV來處理,因為所有這些逗號都會被當作列的分隔符。
import json
with open("testfile.jsons"/span>) as fileobj:
result = [json.load(record) for record in fileobj]
uj5u.com熱心網友回復:
考慮到,"Test.csv "是CSV檔案名,其中有你的兩個條目。請 找到轉儲資料到JSON檔案("Test.json")的代碼。
import csv
import json
def main()。
# Read Test csv having 2 records.
with open("Test.csv"/span>) as csvfile。
data = csv.reader(csvfile)
result = [json.load(record[0]) for record in data ]
# dump csv資料到Test.json檔案。
with open("Test.json"/span>, "w"/span>) as jsonfile:
json.dump(result, jsonfile)
# read Test json file to validate data is dumped correctly or not.
with open("Test.json"/span>, "r"/span>) as jsonfile:
data = json.load(jsonfile.read())
for record in data:
print(record)
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310238.html
標籤:

