2014-01-10 113 views
16

嗨我想從一個json文件中取數據並插入id然後執行POST REST。 我的文件data.json有:Python閱讀JSON文件並修改

{ 
    'name':'myname' 
} 

,我想,這樣的JSON數據看起來像添加ID:

{ 
    'id': 134, 
    'name': 'myname' 
} 

所以,我想:

import json 
f = open("data.json","r") 
data = f.read() 
jsonObj = json.loads(data) 

我無法加載json格式文件。 我該怎麼做才能將json文件轉換爲json對象並添加另一個id值。

+3

這是無效的json。一個字符串應該用**雙引號**包裝。 – falsetru

+0

謝謝你解決了它。 – codeBarer

回答

26

設置項目使用data['id'] = ...

import json 

with open('data.json', 'r+') as f: 
    data = json.load(f) 
    data['id'] = 134 # <--- add `id` value. 
    f.seek(0)  # <--- should reset file position to the beginning. 
    json.dump(data, f, indent=4) 
    f.truncate()  # remove remaining part 
+5

無關:json格式是爲Unicode文本定義的。你可以使用'codecs.open('data.json','r +',encoding ='utf-8')作爲f' – jfs

9

falsetru的解決方案是好的,但有一個小錯誤:

假設原來的「身份證」長度超過5個字符大。當我們隨後使用新的'id'(僅有3個字符的134)轉儲時,從文件中的位置0開始寫入的字符串的長度爲,比原始長度短。額外的字符(如'}')保留在原始內容的文件中。

我解決了通過替換原始文件。

import json 
import os 

filename = 'data.json' 
with open(filename, 'r') as f: 
    data = json.load(f) 
    data['id'] = 134 # <--- add `id` value. 

os.remove(filename) 
with open(filename, 'w') as f: 
    json.dump(data, f, indent=4) 
+0

我更新了答案來修復一個bug。 – falsetru