how to generate a Json object from string in ruby

Viewed 87

I have an array of strings of this format ['config = 3', 'config_b.root.a.b.c = 13'] ; my goal is to create the following json object from them

  {
    "config": 3,
    "config_b": {
      "root": {
        "a": {
          "b": {
            "c": 13
          }
        }
      }
    }
  }

this is my current working approach


# inputs is an array of strings
def create_config(inputs)
  hash={}
  inputs.each do |x|
    value = x.split("=")[1]
    keys = x.split("=")[0].strip.split(".")
    add_item(keys,value,hash)
  end
  print hash
end

# recusive function for adding items
def add_item(keys,value,hash)
  current = keys.shift
  if keys.empty?
    hash[current] = value
  else
    hash[current] = {}
    add_item(keys,value,hash[current])
  end
end

I would like to know if anyone has a better approach for solving this, Thanks

1 Answers

I think I have a solution.

def create_config(inputs)
  inputs.map do |e|
    keys, value = e.split(' = ')
    keys.split('.').reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
  end.reduce(:merge)
end

I tried it with

['config = 3', 'config_b.root.a.b.c = 13']

and got

{"config"=>"3", "config_b"=>{"root"=>{"a"=>{"b"=>{"c"=>"13"}}}}}
Related