迭代JSON数组 - Sinatra

时间:2014-11-21 09:58:25

标签: ruby json sinatra webhooks

我有一个基本的Sinatra应用程序,它接收来自PagerDuty的webhook,抓取一些字段并将新文档插入MongoDB。

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对象而我不知道如何调整代码并遍历数组而不是在DRY中抓取数组中的第一个对象方式。

1 个答案:

答案 0 :(得分: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