2017-02-14 58 views
2

我有一個YAML文件看起來像這樣(用BOT的名字及其參數):YAML以JSON紅寶石

conf_file: 

    pipeline_conf_path: /opt/etc/pipeline.conf 
    runtime_conf_path: /opt/etc/runtime.conf 


    asn_lookup: 
    parameters: 
     database: /opt/var/lib/bots/asn_lookup/ipasnteste.dat 
    group: "Expert" 
    name: "ASN Lookup" 
    module: "one module" 
    description: "modified by " 

    modify: 
    parameters: 
     configuration_path: /opt/var/lib/bots/modify/modify.conf 
    group: "Expert" 
    name: "Modify" 
    module: "one module" 
    description: "modified" 

filter: 
    parameters: 
     filter_action: 
     filter_key: 
     filter_regex: 
     filter_value: 

    group: "Expert" 
    name: "Filter" 
    module: "one module" 
    description: "modified" 

而且我想給每個機器人轉換成JSON。例如用於ASN-查找輸出應該是這樣的:

"asn-lookup": { 
     "parameters": { 
      "database": "/opt/var/lib/bots/asn_lookup/ipasnteste.dat" 
     }, 
     "group": "Expert", 
     "name": "ASN Lookup", 
     "module": "one module", 
     "description": "modified by" 
    } 

我已經有下面的代碼:

def generate_asn_bot 
    config = YAML.load_file('my_conf.yaml') 
    asn = config["conf_file"]["asn_lookup"] 
    puts JSON.pretty_generate(asn) 
end 

,它提供了以下的輸出:

{ 
    "parameters": { 
    "database": "/opt/intelmq/var/lib/bots/asn_lookup/ipasnteste.dat" 
    }, 
    "group": "Expert", 
    "name": "ASN Lookup", 
    "module": "intelmq.bots.experts.asn_lookup.expert", 
    "description": "modified by mfelix" 
} 

但它缺少bot名稱。 所以我添加以下行的代碼:

final = asn['name'] = '"asn-lookup"' + ': ' + asn.to_json 

並使用JSON.pretty_generate(final)但它不工作,引發錯誤:

only generation of JSON objects or arrays allowed (JSON::GeneratorError)

什麼是每個機器人轉換成JSON和添加的最佳途徑機器人名稱在它的開頭?

+0

你爲什麼不只是創建要轉儲(通過與鑰匙「‘ASN-查找’」和值'asn'的映射,然後轉儲結構,而不是雜耍字符串表示的結構'asn'?你是否收到錯誤信息?如果是這樣的話是什麼?爲什麼這不起作用? – Anthon

+0

這是一個非常好的主意!謝謝 我得到的錯誤是「只允許生成JSON對象或數組(JSON :: GeneratorError)「,但這是因爲變量」最終「是一個字符串.. 我沒有想法來解決這個問題,謝謝你的建議@Anthon – mf370

+0

如果我知道任何ruby語法,我會把它放在一個答案;-)。如果你找到了,你可以自回答您的文章和接受的答案 – Anthon

回答

2
def generate_asn_bot 
    config = YAML.load_file('my_conf.yaml') 
    asn = config["conf_file"]["asn_lookup"] 
    hash = Hash.new 
    hash["asn-lookup"] = asn 
    puts JSON.pretty_generate(hash) 
end 

只是將所有內容保存到哈希中!

0
ruby -ryaml -rjson -e "puts YAML.load_file('my_conf.yaml').to_json"