2017-02-10 6 views
1

Ich habe eine JSON-Datei besteht aus Bot-Namen und deren Parameter und Konfigurationen, und es sieht wie folgt aus:JSON-Datei in Ruby-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." 
    }, 
    "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" 
    } 
} 

Und ich möchte, dass es zu einem Ruby-Hash mit den Bot Namen analysieren "csv-collector" und "csv-parser" als Schlüssel und der Rest des Inhalts als Werte. Etwas wie folgt aus:

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." 
      } 
     } 

Ich habe mehrere Bots so dass dies auch für die anderen gültig sein muss.

Ich habe bereits den folgenden Code:

require "json" 

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

aber gibt mir die folgende Fehlermeldung:

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

Ich bin neu in Ruby und ich weiß nicht, sehr gut, wie zu analysieren die JSON-Datei zu einem Ruby Hash

Antwort

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