2017-02-06 73 views
0

我試圖將JSON對象附加到文本文件中的現有JSON對象。我的第一組數據看起來很喜歡這個。Python - 將JSON對象附加到存在的JSON對象

data = [ 
     { 
      "username": "Mike", 
      "code": "12345", 
      "city": "NYC" 
     } 
     ] 

然後,我需要另一套JSON對象追加到現有的文件看起來像這樣:

data = [ 
     { 
      "username": "Mike", 
      "code": "12345", 
      "city": "NYC" 
     }, 
     { 
      "username": "Kelly", 
      "code": "56789", 
      "city": "NYC" 
     } 
     ] 

當我嘗試運行:

with open('data2.txt', 'a') as outfile: 
    json.dump(data, outfile) 

我的數據是不是在正確的JSON格式。你能建議如何正確追加到文本文件?

+0

你不能只追加到一個文本文件,並期望它以某種方式知道如何在JSON格式。你必須讀取文件,轉換成json,然後添加你的值並重新寫入 – Falmarri

回答

0

首先從文件中讀取數據。

with open('data2.txt') as data_file:  
    old_data = json.load(data_file) 

然後將數據追加到老數據

data = old_data + data 

然後重寫整個文件。

with open('data2.txt', 'w') as outfile: 
    json.dump(data, outfile) 
0

這可能不是處理您的要求最Python的方式,但我希望它會與你可能會遇到的一些問題有所幫助。我將加載和轉儲包裝到try-except手鐲中,以使代碼更加健壯。 對我自己來說最大的驚喜是,當打開文件作爲輸出文件而不是'a'時,而是'w'。然而,如果你認爲你已經在「data.append(data1)」行中追加了,這是非常有意義的,所以在轉儲到文件時不需要追加兩次。

data = [{"username": "Mike", "code": "12345", "city": "NYC"}] 
data1 = {"username": "Kelly", "code": "56789", "city": "NYC"} 
data2 = {"username": "Bob", "code": "12222", "city": "NYC"} 

try: 
    with open('append.txt', 'r') as fin: 
     data = json.load(fin) 
except FileNotFoundError as exc: 
    pass 

try: 
    if data: 
     data.append(data1) 
     with open('append.txt', 'w') as fout: 
      json.dump(data, fout) 
except UnboundLocalError as exc: 
    with open('append.txt', 'w') as fout: 
     json.dump(data, fout)