2015-11-08 11 views
0

我一直在尋找網絡,我找不到添加新的JSON數據到數組的方法。將新的JSON數據存儲到python中的現有文件中

示例:我想通過python添加player_two,player_three。

{ 
    "players": { 
    "player_one": { 
     "name": "Bob", 
     "age": "0", 
     "email": "[email protected]" 
    } 
    } 
} 

我怎樣才能實現通過蟒蛇這樣做呢?

我已經試過什麼:

with open("/var/www/html/api/toons/details.json", 'w') as outfile: 
       json.dump(avatarDetails, outfile) 
+0

你試過了嗎?你有什麼錯誤? –

+0

我只嘗試過json.dumps,但是什麼都不做。 – brownzilla

+1

將現有的JSON加載到Python字典中,然後根據需要對其進行變異並保存完成。 – chucksmash

回答

2

下面是一個簡單的例子,讀取該文件作爲一個字典,更新字典,然後使用json.dumps()來獲取JSON數據:

import json 

# open your jsonfile in read mode 
with open('jsonfile') as f: 
    # read the data as a dict use json.load() 
    jsondata = json.load(f) 

# add a new item into the dict 
jsondata['players']['player_two'] = {'email': '[email protected]', 'name': 'Kevin', 'age': '0'} 

# open that file in write mode 
with open('jsonfile', 'w') as f: 
    # write the data into that file 
    json.dump(jsondata, f, indent=4, sort_keys=True) 

現在該文件看起來像:

{ 
    "players": { 
     "player_one": { 
      "age": "0", 
      "email": "[email protected]", 
      "name": "Bob" 
     }, 
     "player_two": { 
      "age": "0", 
      "email": "[email protected]", 
      "name": "Kevin" 
     } 
    } 
} 
+1

使用'json.load(f)'和'json.dump(data,f,...)'會比需要顯式讀取文件的'json.loads()'和'json.dumps()寫道。 – mhawke

+0

@mhawke謝謝,我編輯過。這麼好的想法:) –

+0

有沒有辦法接受json響應,然後將其插入現有的'player'數組中? – brownzilla

1

假設您的文件包含此JSON:

{ 
    "players": { 
    "player_one": { 
     "name": "Bob", 
     "age": "0", 
     "email": "[email protected]" 
    } 
    } 
} 

可以使用json.load()解析數據到Python字典:

with open('/var/www/html/api/toons/details.json') as f: 
    data = json.load(f) 

添加新的球員:

data['players']['player_two'] = dict(name='Bobbie', age=100, email='[email protected]') 
data['players']['player_three'] = dict(name='Robert', age=22, email='[email protected]') 

然後回到它保存到一個文件:

with open('/var/www/html/api/toons/details.json', 'w') as f: 
    json.dump(data, f) 
相關問題