2014-11-21 165 views
0

我有一个基本的Sinatra应用程序,它从PagerDuty接收一个webhook,抓取一些字段并在MongoDB中插入一个新文档。通过JSON数组迭代 - Sinatra

post '/webhooks/pagerduty/' do 

    request.body.rewind 
    json = JSON.parse(request.body.read) 

    @pd_id = json["messages"][0]["data"]["incident"]["id"] 
    @ts = json["messages"][0]["data"]["incident"]["created_on"] 
    @status = json["messages"][0]["data"]["incident"]["status"] 
    @host = json["messages"][0]["data"]["incident"]["trigger_summary_data"]["HOSTNAME"] 
    @description = json["messages"][0]["data"]["incident"]["trigger_summary_data"]["SERVICEDESC"] 
    @state = json["messages"][0]["data"]["incident"]["trigger_summary_data"]["SERVICESTATE"] 

    # MongoDB connection code omitted 

    coll = db.collection('incidents') 

    _id = SecureRandom.hex 

    if @status != "resolved" 

    coll.insert({ :_id => _id, :pd_id => @pd_id, :ts => @ts, :status => @status, :host => @host, :description => @description, :state => @state, :db_type => @db_type }) 

    else 

    coll.update({ :pd_id => @pd_id }, { "$set" => { :status => @status }}) 

    end 

    status 200 

end 

这工作得很好,但问题是,有时PagerDuty发送阵列在多个JSON对象,我不知道如何调整代码,并通过遍历数组的数组中抓住了第一个对象,而不是一种干的方式。

+0

为什么不展示JSON的最小示例,这样我们就可以看到你在说什么,而不是让我们想象它呢? – 2014-11-21 17:32:17

+0

这只是一个JSON数组:{“messages”:[{“field”:“value”},{“field”:“value”}]} – kylemclaren 2014-11-22 22:05:32

回答

1

由于JSON.parse(request.body.read)["messages"]Array对象,因此您可以对其执行Array#each调用。

JSON.parse(request.body.read)["messages"].each do |element| 
    processed = process(element) 
    processed["status"] == "resolved" ? update(processed) : insert(processed) 
end 

def process(element) 
    # extract the required data from the json object 
    # return a Hash with the data 
end 

def insert(hash) 
    # insert 
end 

def update(hash) 
    # update 
end 
+0

非常感谢您的快速响应。我会试试这个,让你知道:) – kylemclaren 2014-11-22 22:06:01