RubyOnRails + 尝试将 JSON 转换为特定格式

RubyOnRails + Trying to convert JSON into specific format

现有数据:

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

预计:

[
    "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"
    }
]

将对象转换为所需格式的一种方法是使用正则表达式提取登录号和相关属性,如下所示:

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

然后,给定示例中的初始数组,此方法应return以下内容:

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