Ruby 从JSON输出构建数据结构

Ruby 从JSON输出构建数据结构,ruby,json,file,loops,Ruby,Json,File,Loops,嗨,我正在写一个脚本,从票务系统中提取数据。一旦它提取了数据,它就会分析它的内容,如果它的内容符合特定的标准,那么它需要构建一个数据结构文件,该文件将转储到同一服务器中 我能够以JSON格式解析数据,下面列出了内容: [{"id"=>10423, "type"=>"Ticket", "lastUpdated"=>"2014-11-04T10:58:47Z", "shortSubject"=>"FOO STATUS UPDATE", "shortDetail

嗨,我正在写一个脚本,从票务系统中提取数据。一旦它提取了数据,它就会分析它的内容,如果它的内容符合特定的标准,那么它需要构建一个数据结构文件,该文件将转储到同一服务器中

我能够以JSON格式解析数据,下面列出了内容:

[{"id"=>10423,
  "type"=>"Ticket",
  "lastUpdated"=>"2014-11-04T10:58:47Z",
  "shortSubject"=>"FOO STATUS UPDATE",
  "shortDetail"=>"Reply to this message if all systems are functional..",
  "displayClient"=>"No Client",
  "updateFlagType"=>0,
  "prettyLastUpdated"=>"54 minutes ago",
  "latestNote"=>
   {"id"=>16850,
    "type"=>"TechNote",
    "mobileListText"=>"<b>t. trust: </b> All Systems are OK",
    "noteColor"=>"clear",
    "noteClass"=>"bubble right"}},

 {"id"=>10422,
  "type"=>"Ticket",
  "lastUpdated"=>"2014-11-04T10:54:07Z",
  "shortSubject"=>"FOO STATUS UPDATE",
  "shortDetail"=>"Reply to this message if all systems are functional..",
  "displayClient"=>"No Client",
  "updateFlagType"=>0,
  "prettyLastUpdated"=>"58 minutes ago",
  "latestNote"=>nil},

 {"id"=>10421,
  "type"=>"Ticket",
  "lastUpdated"=>"2014-11-04T10:53:17Z",
  "shortSubject"=>"FOO STATUS UPDATE",
  "shortDetail"=>"Reply to this message if all systems are functional..",
  "displayClient"=>"No Client",
  "updateFlagType"=>0,
  "prettyLastUpdated"=>"59 minutes ago",
  "latestNote"=>nil}]
但是,根据上面的数据,只有一张票的所有系统都正常,这意味着只有一张票得到了回复,它只应该写这样的内容:

{"LastUpdate":1415130257,"Service":[{"time":"11-04-2014 10:58:47 GMT","region:":"","id":"","description":"All Systems are OK","service":""}]}
而是重复这唯一一张已经被回复了好几次的票证

到目前为止,这是我的代码:

require 'rubygems'
require 'json'
require 'net/http'
require 'highline/import'
require 'pp'
require 'logger'



@usersol='foo'
@passol= 'foo123'
@urlsol= "http://dev-webhelpdesk.foo.corp:8081/helpdesk/WebObjects/Helpdesk.woa/ra/Tickets?list=group&page=1&limit=#{@limit}&username=#{@usersol}&password=#{@passol}"
@limit = '25'
@log = @log= Logger.new( 'message_solar.log')






 def ticket_data                                              #looks for ticket data in solarwinds
    resp = Net::HTTP.get_response(URI.parse(@urlsol))
    url_output = resp.body
    JSON.parse(url_output)
  end

#CRONJOB THAT START ALL
#echo "Reply to this message if all systems are functional.." | mail -r noc@foo.com  -s "FOO STATUS UPDATE:" noc-team@FOO.com >> /dev/null
                                          # Looking for all the tickets  with the following content
                                          # ticket id, ticket subject and content
  def search_allok(allok)
    description = []
    allok.each do |systems|
      output1 = systems.has_key?'id'
      if output1
        systems.values_at('shortSubject').each do | subject |
         output2 = subject.match(%r(TRUST STATUS UPDATE))
         if output2
           latestnote = systems.values_at('latestNote')
           latestnote.each do |content|
            if content
             final = content.values_at('mobileListText')
             final_ok = final[0].sub!(/^\<b\>.*\<\/b\>\s/, "")
             systems_ok = final_ok.match(%r(All Systems are OK))
                if systems_ok
                  ids = systems['id']
                  notify = {"LastUpdate" => Time.now.to_i, "Service" => []}
                  allok.each do |lastup|
                    reference = lastup.has_key? 'id'
                    if reference
                      timeid = lastup.values_at('lastUpdated')
                      timeid.each do |lines|
                        final=lines.split(/[-, T, Z]/)
                        notify["Service"] << { "time" => "#{final[1]}-#{final[2]}-#{final[0]} #{final[3]} GMT", "region:" => "", "id" => "#{ids}", "description" => "#{systems_ok}" , "service" => ''}
                      end
                    end
                  end
                  File.open("notify.json", "w") do |fileformatted|
                    fileformatted.puts (JSON.dump(notify))
                  end
                 else
                  time = Time.now
                  @log.info("#{time} - Ticket ID #{systems['id']} has not being updated")
                end
            else
              @log.info("#{time} - Ticket ID #{systems['id']} has not being reply")
            end
           end
         end
       end
      end
    end
  end







                                    # If the content is there then it need to create
                                    # the data structure including the lastupdated                                                    
                                    # (time when it run the script), and the lastupdate for the ticket                                                                                  
                                    # and the description All Systems OK

#This method below I added to the one above, but I was thinking on doing it separate but I encouter issues passing the information needed from above to below

  def datastructure(format_file)            #creates JSON file lastupdated of each ticket in the queue
    notify = {"LastUpdate" => Time.now.to_i, "Service" => []}
     format_file.each do |lastup|
       reference = lastup.has_key? 'id'
       if reference
         timeid = lastup.values_at('lastUpdated')
         timeid.each do |lines|
          final=lines.split(/[-, T, Z]/)
            notify["Service"] << { "time" => "#{final[1]}-#{final[2]}-#{final[0]} #{final[3]} GMT", "region:" => "", "id" => "", "description" => region , "service" => ''}
         end
       end
    end
    File.open("notify.json", "w") do |fileformatted|
      fileformatted.puts (JSON.dump(notify))
    end
  end

#ticket_data
#datastructure(ticket_data)
search_allok(ticket_data)
需要“rubygems”
需要“json”
需要“net/http”
需要“高端/进口”
需要“pp”
需要“记录器”
@usersol='foo'
@passol='foo123'
@urlsol=”http://dev-webhelpdesk.foo.corp:8081/helpdesk/WebObjects/Helpdesk.woa/ra/Tickets?list=group&page=1&limit=#{@limit}&username={@usersol}&password={@passol}”
@限制='25'
@log=@log=Logger.new('message\u solar.log')
def ticket#u data#在太阳林中查找票据数据
resp=Net::HTTP.get\u响应(URI.parse(@urlsol))
url_输出=响应主体
parse(url_输出)
结束
#开始一切的工作
#echo“如果所有系统都正常运行,则回复此消息…”邮件-rnoc@foo.com-s“FOO状态更新:”国家奥委会-team@FOO.com>>/dev/null
#查找所有包含以下内容的票
#票证id、票证主题和内容
def搜索分配(分配)
description=[]
所有do |系统|
output1=系统。是否有密钥?'id'
如果输出1
系统。在(“短主题”)处的值。每个都有主题|
output2=主题匹配(%r(信任状态更新))
如果输出2
latestnote=systems.values\u at('latestnote')
最新注释。每个都有内容|
如果内容
final=content.values\u at('mobileListText')
final\u ok=final[0]。sub!(/^\.\\s/,“”)
系统正常=最终正常。匹配(%r(所有系统正常))
如果系统正常
ids=系统['id']
notify={“LastUpdate”=>Time.now.to_i,“Service”=>[]}
每件事都要坚持下去|
reference=lastup.has_key?'身份证
如果参考
timeid=lastup.values\u在('lastUpdated')
timeid.每个do |行|
最终=行。拆分(/[-,T,Z]/)
通知[“服务”]“{final[1]}-{final[2]}-{final[0]}{final[3]}GMT”,“地区:=>”,“id”=>“{ids}”,“说明”=>“{systems_ok}”,“服务”=>”
结束
结束
结束
File.open(“notify.json”,“w”)do | fileformatted|
fileformatted.put(JSON.dump(notify))
结束
其他的
时间=现在
@log.info(“#{time}-票据ID#{systems['ID']}尚未更新”)
结束
其他的
@log.info(“#{time}-Ticket ID#{systems['ID']}尚未被回复”)
结束
结束
结束
结束
结束
结束
结束
#如果内容在那里,那么它需要创建
#数据结构,包括最新更新的
#(运行脚本的时间),以及票证的最新更新
#说明所有系统正常
#下面的方法我添加到上面的方法中,但我想单独使用,但我遇到了将所需信息从上面传递到下面的问题
def datastructure(format_file)#创建队列中每个票证的JSON文件lastupdated
notify={“LastUpdate”=>Time.now.to_i,“Service”=>[]}
格式化_file.each do|lastup|
reference=lastup.has_key?'身份证
如果参考
timeid=lastup.values\u在('lastUpdated')
timeid.每个do |行|
最终=行。拆分(/[-,T,Z]/)
通知[“服务”]“#{final[1]}-#{final[2]}-#{final[0]}{final[3]}GMT”,“地区:=>,“id”=>,“说明”=>地区,“服务”=>'}
结束
结束
结束
File.open(“notify.json”,“w”)do | fileformatted|
fileformatted.put(JSON.dump(notify))
结束
结束
#票证数据
#数据结构(票证数据)
搜索所有(票证数据)

您编写的代码基本上是使用ruby的map和select方法实现的一个迂回版本。请参阅本文:

您能否将其简化为您想要实现的内容的最小示例?如果您想要附加到文件中,您需要使用
a
而不是
w
我想要实现的是以下结构:{“LastUpdate”:1415130257,“Service”:[{“time”:“11-04-2014 10:58:47 GMT”,“region::”,“id:“description:“所有系统都正常”,“服务:”},{“时间”:“11-04-2014 10:54:07 GMT”,“地区:”,“id”:“描述”:“所有系统正常”,“服务:”},{“时间”:“11-04-2014 10:53:17 GMT”,“地区:”,“id”:“描述”:“所有系统正常”,“服务:”}]
require 'rubygems'
require 'json'
require 'net/http'
require 'highline/import'
require 'pp'
require 'logger'



@usersol='foo'
@passol= 'foo123'
@urlsol= "http://dev-webhelpdesk.foo.corp:8081/helpdesk/WebObjects/Helpdesk.woa/ra/Tickets?list=group&page=1&limit=#{@limit}&username=#{@usersol}&password=#{@passol}"
@limit = '25'
@log = @log= Logger.new( 'message_solar.log')






 def ticket_data                                              #looks for ticket data in solarwinds
    resp = Net::HTTP.get_response(URI.parse(@urlsol))
    url_output = resp.body
    JSON.parse(url_output)
  end

#CRONJOB THAT START ALL
#echo "Reply to this message if all systems are functional.." | mail -r noc@foo.com  -s "FOO STATUS UPDATE:" noc-team@FOO.com >> /dev/null
                                          # Looking for all the tickets  with the following content
                                          # ticket id, ticket subject and content
  def search_allok(allok)
    description = []
    allok.each do |systems|
      output1 = systems.has_key?'id'
      if output1
        systems.values_at('shortSubject').each do | subject |
         output2 = subject.match(%r(TRUST STATUS UPDATE))
         if output2
           latestnote = systems.values_at('latestNote')
           latestnote.each do |content|
            if content
             final = content.values_at('mobileListText')
             final_ok = final[0].sub!(/^\<b\>.*\<\/b\>\s/, "")
             systems_ok = final_ok.match(%r(All Systems are OK))
                if systems_ok
                  ids = systems['id']
                  notify = {"LastUpdate" => Time.now.to_i, "Service" => []}
                  allok.each do |lastup|
                    reference = lastup.has_key? 'id'
                    if reference
                      timeid = lastup.values_at('lastUpdated')
                      timeid.each do |lines|
                        final=lines.split(/[-, T, Z]/)
                        notify["Service"] << { "time" => "#{final[1]}-#{final[2]}-#{final[0]} #{final[3]} GMT", "region:" => "", "id" => "#{ids}", "description" => "#{systems_ok}" , "service" => ''}
                      end
                    end
                  end
                  File.open("notify.json", "w") do |fileformatted|
                    fileformatted.puts (JSON.dump(notify))
                  end
                 else
                  time = Time.now
                  @log.info("#{time} - Ticket ID #{systems['id']} has not being updated")
                end
            else
              @log.info("#{time} - Ticket ID #{systems['id']} has not being reply")
            end
           end
         end
       end
      end
    end
  end







                                    # If the content is there then it need to create
                                    # the data structure including the lastupdated                                                    
                                    # (time when it run the script), and the lastupdate for the ticket                                                                                  
                                    # and the description All Systems OK

#This method below I added to the one above, but I was thinking on doing it separate but I encouter issues passing the information needed from above to below

  def datastructure(format_file)            #creates JSON file lastupdated of each ticket in the queue
    notify = {"LastUpdate" => Time.now.to_i, "Service" => []}
     format_file.each do |lastup|
       reference = lastup.has_key? 'id'
       if reference
         timeid = lastup.values_at('lastUpdated')
         timeid.each do |lines|
          final=lines.split(/[-, T, Z]/)
            notify["Service"] << { "time" => "#{final[1]}-#{final[2]}-#{final[0]} #{final[3]} GMT", "region:" => "", "id" => "", "description" => region , "service" => ''}
         end
       end
    end
    File.open("notify.json", "w") do |fileformatted|
      fileformatted.puts (JSON.dump(notify))
    end
  end

#ticket_data
#datastructure(ticket_data)
search_allok(ticket_data)