Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YAML to JSON Ruby

Tags:

json

ruby

yaml

I have a YAML file that looks like this (with bot names and their parameters):

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"

And I would like to convert each bot to JSON. For example for the asn-lookup the output should be something like:

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

I already have the following code:

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

and it gives the following output:

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

But it's missing the bot name. So I added the following line to the code:

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

And use JSON.pretty_generate(final) but it's not working, throwing the error:

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

What is the best way to convert each bot into JSON and add bot name at the beginning of it?

like image 530
mf370 Avatar asked Mar 10 '23 21:03

mf370


1 Answers

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

Just saved everything into a Hash!

like image 97
mf370 Avatar answered Mar 21 '23 01:03

mf370