Home > Mobile >  RubyOnRails Trying to convert JSON into specific format
RubyOnRails Trying to convert JSON into specific format

Time:05-18

Existing Data:

[
 {"name"=> "login[0][id]", "value"=> "10"},
 {"name"=> "login[0][name]", "value"=> "AAA"}, 
 {"name"=> "login[0][login]", "value"=> "login-1"}, 
 {"name"=> "login[0][password]", "value"=> "password-1"},
 {"name"=> "login[0][notes]", "value"=> "url-1"}, 
 {"name"=> "login[1][id]", "value"=> "15"}, 
 {"name"=> "login[1][name]", "value"=> "BBB"}, 
 {"name"=> "login[1][login]", "value"=> "admin"}, 
 {"name"=> "login[1][password]", "value"=> "admin-pwd"},
 {"name"=> "login[1][notes]", "value"=> "url-2"}
]

Expected:

[
    "0" => {
        "id": "10",
        "name": "AAA", 
        "login", "login-1",
        "password": "password-1",
        "notes": "url-1"
    }, 
    "1" => {
        "id": "15",
        "name": "BBB", 
        "login", "ladmin",
        "password": "admin-pwd",
        "notes": "url-2"
    }
]

CodePudding user response:

One approach to convert the object to your desired format is to use a regex to extract the login number and associated attributes, like so:

def convert(array)
  name_regex = /^login\[(?<number>\d )\]\[(?<attribute>\S )\]/
  result = {}

  array.each do |obj|
    match = obj["name"].match(name_regex)
    next if match.nil?

    result[match[:number]] ||= {}
    result[match[:number]][match[:attribute]] = obj["value"]
  end
  
  result
end

Then, given the initial array in your example, this method should return the following:

array = [
  { "name" => "login[0][id]", "value" => "10" },
  { "name" => "login[0][name]", "value" => "AAA" }, 
  { "name" => "login[0][login]", "value" => "login-1" }, 
  { "name" => "login[0][password]", "value" => "password-1" },
  { "name" => "login[0][notes]", "value" => "url-1" }, 
  { "name" => "login[1][id]", "value" => "15" }, 
  { "name" => "login[1][name]", "value" => "BBB" }, 
  { "name" => "login[1][login]", "value" => "admin" }, 
  { "name" => "login[1][password]", "value" => "admin-pwd" },
  { "name" => "login[1][notes]", "value" => "url-2" }
]

convert(array)

#=> {"0"=>{"id"=>"10", "name"=>"AAA", "login"=>"login-1", "password"=>"password-1", "notes"=>"url-1"}, "1"=>{"id"=>"15", "name"=>"BBB", "login"=>"admin", "password"=>"admin-pwd", "notes"=>"url-2"}}
  • Related