我有一个看起来像这样的 YAML 文件(带有机器人名称及其参数):
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"
Run Code Online (Sandbox Code Playgroud)
我想将每个机器人转换为 JSON。例如,对于 asn-lookup,输出应该是这样的:
"asn-lookup": {
"parameters": {
"database": "/opt/var/lib/bots/asn_lookup/ipasnteste.dat"
},
"group": "Expert",
"name": "ASN Lookup",
"module": "one module",
"description": "modified by"
}
Run Code Online (Sandbox Code Playgroud)
我已经有以下代码:
def generate_asn_bot
config = YAML.load_file('my_conf.yaml')
asn = config["conf_file"]["asn_lookup"]
puts JSON.pretty_generate(asn)
end
Run Code Online (Sandbox Code Playgroud)
它给出了以下输出:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
但它缺少机器人名称。所以我在代码中添加了以下行:
final = asn['name'] = '"asn-lookup"' + ': ' + asn.to_json
Run Code Online (Sandbox Code Playgroud)
并使用JSON.pretty_generate(final)但它不起作用,抛出错误:
只允许生成 JSON 对象或数组 (JSON::GeneratorError)
将每个机器人转换为 JSON 并在其开头添加机器人名称的最佳方法是什么?
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
Run Code Online (Sandbox Code Playgroud)
只是将所有内容保存到哈希中!
ruby -ryaml -rjson -e "puts YAML.load_file('my_conf.yaml').to_json"
Run Code Online (Sandbox Code Playgroud)