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"