2017-02-10 115 views
1

我有機器人的名字和他們的參數和配置組成的JSON文件,它看起來像這樣:JSON文件到Ruby哈希

{ 
    "csv-collector": { 
     "parameters": { 
      "delete_file": false, 
      "feed": "FileCollector", 
      "provider": "ola", 
      "path": "/tmp/", 
      "postfix": ".csv", 
      "rate_limit": 300 
     }, 
     "group": "Collector", 
     "name": "Fileinput", 
     "module": "abc", 
     "description": "Fileinput collector fetches data from a file." 
    }, 
    "csv-parser": { 
     "parameters": { 
      "columns": "classification.type,destination.ip", 
      "default_url_protocol": "http://", 
      "delimiter": ",", 
      "skip_header": true, 
      "type": "c&c" 
     }, 
     "group": "Parser", 
     "name": "Generic CSV", 
     "module": "efg", 
     "description": "Generic CSV Parser is a generic bot" 
    } 
} 

而且我想它與機器人的名字解析到一個Ruby的Hash 「csv-collector」和「csv-parser」作爲鍵和其餘內容作爲值。 事情是這樣的:

my_hash = {"csv-collector" => {"parameters": { 
       "delete_file": false, 
       "feed": "FileCollector", 
       "provider": "ola", 
       "path": "/tmp/", 
       "postfix": ".csv", 
       "rate_limit": 300 
      }, 
      "group": "Collector", 
      "name": "Fileinput", 
      "module": "abc", 
      "description": "Fileinput collector fetches data from a file." 
      } 
     } 

我有幾個機器人因此必須爲他人有效爲好。

我已經有下面的代碼:

require "json" 

def read_file 
    temp = Hash.new 
    file = JSON.parse(File.read('mybotsfile.conf')) 
    file.each { |bot| temp << bot} 
    puts temp 
end 

不過是給我下面的錯誤:

`undefined method `<<' for {}:Hash (NoMethodErr`or) 

我是新來的Ruby和我不很清楚如何解析JSON文件到紅寶石哈希

回答

5
require 'json' 
file = File.read('your-json-file.json') 
result_hash = JSON.parse(file)