2017-02-27 88 views
-5

回報我想用python腳本

"messages": [ 
    { 
     "text": "testing", 
     "ts": "1479967441.000004", 
     "user": "ray", 
     "type": "message", 
     "bot_id": "B379PT5AT" 
    },  
    { 
     "text": "SWAT start", 
     "type": "message", 
     "user": "john", 
     "ts": "1479967379.000003" 
    }, 
    { 
     "text": "SWAT close", 
     "type": "message", 
     "user": "ray",  
     "ts": "1479967379.000003" 
    }, 

另一個參數添加到JSON文件我想補充的另一個參數

"messages": [ 
    { 
     "text": "testing", 
     "ts": "1479967441.000004", 
     "user": "ray", 
     "type": "message", 
     "bot_id": "B379PT5AT" 
     "icon": "URL...." 
    }, 
    { 
     "text": "SWAT start", 
     "type": "message", 
     "user": "john", 
     "ts": "1479967379.000003" 
     "icon": "URL...." 
    }, 
    { 
     "text": "SWAT close", 
     "type": "message", 
     "user": "ray", 
     "ts": "1479967379.000003" 
     "icon": "URL...." 
    }, 

代碼:

import simplejson 
with open ('automation.json')as json_data: 
    data = simplejson.loads(json_data) 
    for r in data['messages']: 
     key = messages['icon'] 
     messages["icon"] = ("testing") 

outdata = simplejson.dumps(data) 
+0

這個圖標字段對每個對象都是一樣的嗎?如果沒有,那麼你會從哪裏得到這些信息? –

+0

到目前爲止您嘗試過什麼? –

+0

我得到了一個json文件 我想運行一個python腳本,以便我可以進行上述更改 –

回答

0

你幾乎擁有它。循環訪問data['messages']訪問字典列表,這就是爲什麼您的任務不能正常工作。您必須先訪問字典,然後進行分配。

import json 
with open('automation.json') as data_file: 
    data = json.load(data_file)['messages'] # you now have a the json as a python object. 
# If you want to always add the same value to each dictionary 
data = {d['icon'] = 'A Value you want' for d in data} # d represents a dictionary in data['messages'] 

# other wise, lets say the icon is linked to the user: 
icon_urls = {'john': 'http://someurl.com', 'ray': 'http://someotherurl.com'} 
data = {d['icon'] = icon_urls[d['user']] for d in data}