我有一個 .json 檔案,其中包含如下所示的物件:
[
{
"a": "0.038",
"b": "1",
"c": "0"
},
{
"a": "0.040",
"b": "1",
"c": "0"
},
...
]
我有一個 .csv 檔案,如下所示:
d e f
0.00 0.00 0.00
0.02 -0.08 -0.08
0.04 -0.32 -0.32
...
我想修改 .json 檔案以從 .csv 檔案中添加新的鍵/值對,但我不想在檔案末尾添加新專案,而是從 .csv 中添加一行被添加到每個元素的末尾。所以新的 .json 看起來像這樣:
[
{
"a": "0.038",
"b": "1",
"c": "0",
"d": "0.00",
"e": "0.00",
"f": "0.00"
},
{
"a": "0.040",
"b": "1",
"c": "0",
"d": "0.02",
"e": "-0.08",
"f": "-0.08""
},
...
]
我嘗試了不同的方法(例如使用 append() 或 update()),但他們要么將 .csv 資料添加到 .json 檔案的完整末尾,要么嘗試將整個 .csv 資料添加到第一個元素的末尾在 .json 中。在我看來,我需要做的是,從 json 物件創建一個字典,將 csv 資料也加載到字典中,遍歷每個 json 元素,然后從 csv 資料中添加一行,創建一個新的 json目的。但是我沒有得到我想要的輸出,或者我遇到了無法附加到字典的問題。這是我現有的代碼:
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
with open("existing.json") as json_file:
data = json.load(json_file)
json_file.close() # Close the JSON file
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
for item in data:
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
item.update(row)
#convert python jsonArray to JSON string and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(data, indent = 4)
jsonf.write(jsonString)
#decide the 2 file paths according to your file system
csvFilePath = r'C:\Users\\Downloads\filename.csv'
jsonFilePath = r'C:\Users\\Desktop\filename.json'
csv_to_json(csvFilePath, jsonFilePath)
uj5u.com熱心網友回復:
您的問題是您有嵌套回圈。這會產生幾個問題:
for item in data:
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
item.update(row)
csvReader = csv.DictReader(csvf)做csvReader一個迭代器。csvReader一旦您在第一次迭代結束時通讀了 的所有行for item in data,該迭代器就會用盡并且不會再產生任何行。因此,對于后續item的 s indata,您將永遠不會有任何行 incsvReader。您可以通過執行來解決此問題csvReader = list(csv.DictReader(...)),這會將所有行讀入一個串列,您可以在該串列上進行任意次數的迭代。- 一旦你解決了這個問題。您使用. _
item_ _ _ 這不是您想要的,因為您只希望th用第th 行更新。datacsvReaderiitemi
要解決此問題,您需要zip()兩個迭代器,以便您data同時迭代csvReader:
for item, row in zip(data, csvReader):
item.update(row)
請注意,由于在這種情況下您不會多次迭代csvReader,因此它不需要是一個串列并且您的原始定義csvReader = csv.DictReader(csvf)就足夠了(您可能需要csvReader = csv.DictReader(csvf, delimiter="\t")指定分隔符,默認情況下假定為逗號)
現在你有data =
[{'a': '0.038', 'b': '1', 'c': '0', 'd': '0.00', 'e': '0.00', 'f': '0.00'},
{'a': '0.040', 'b': '1', 'c': '0', 'd': '0.02', 'e': '-0.08', 'f': '-0.08'}]
uj5u.com熱心網友回復:
您需要一起迭代 json 陣列和 csv 陣列的行。最簡單的方法是將zip()它們放在一起并回圈。這將為您提供相應的行,以便您可以使用 csv 中的 dict 更新 json 行:
def csv_to_json(csvFilePath, jsonFilePath):
with open("existing.json") as json_file:
data = json.load(json_file)
with open(csvFilePath, encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for row_json, row_csv in zip(data, csvReader):
row_json.update(row_csv)
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(data, indent = 4)
jsonf.write(jsonString)
使用您的資料,這將撰寫一個如下所示的檔案:
[{
"a": "0.038",
"b": "1",
"c": "0",
"d": "0.00",
"e": "0.00",
"f": "0.00"
},
{
"a": "0.040",
"b": "1",
"c": "0",
"d": "0.02",
"e": "-0.08",
"f": "-0.08"
}]
uj5u.com熱心網友回復:
用于zip將兩個串列壓縮在一起并組合字典:
>>> json_data = [
... {
... "a": "0.038",
... "b": "1",
... "c": "0"
... },
... {
... "a": "0.040",
... "b": "1",
... "c": "0"
... },
... ]
>>>
>>> csv_data = [
... {
... "d": "0.00",
... "e": "0.00",
... "f": "0.00"
... },
... {
... "d": "0.02",
... "e": "-0.08",
... "f": "-0.08"
... }
... ]
>>> from pprint import pprint
>>> pprint([j | c for j, c in zip(json_data, csv_data)])
[{'a': '0.038', 'b': '1', 'c': '0', 'd': '0.00', 'e': '0.00', 'f': '0.00'},
{'a': '0.040', 'b': '1', 'c': '0', 'd': '0.02', 'e': '-0.08', 'f': '-0.08'}]
uj5u.com熱心網友回復:
在此處將 2 個字典合并到一個運算式中。假設兩個字典串列的長度相同:
list1 = [
{
"a": "0.038",
"b": "1",
"c": "0"
},
{
"a": "0.040",
"b": "1",
"c": "0"
}
]
list2 = [
{
"d": "0.00",
"e": "0.00",
"f": "0.00"
},
{
"d": "0.02",
"e": "-0.08",
"f": "-0.08"
}]
然后迭代任何串列的長度:
>>> result = [{**list1[i], **list2[i]} for i in range(len(list1))]
>>> result
[{'a': '0.038', 'b': '1', 'c': '0', 'd': '0.00', 'e': '0.00', 'f': '0.00'}, {'a': '0.040', 'b': '1', 'c': '0', 'd': '0.02', 'e': '-0.08', 'f': '-0.08'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452080.html
