ruby-on-railsrubyregexjsonwufoo

How to scan single line params string and return two arrays?


I have following single line string:

params = {"FieldStructure"=>"{\"Fields\":[{\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},{\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}", "Field6"=>"tettetette", "Field5"=>"test@tessss.pl", "EntryId"=>"25"}

Formated version:

params = {
  "FieldStructure"=>"
    {\"Fields\":[
      {\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},
      {\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}",
    "Field6"=>"tettetette", 
    "Field5"=>"test@tessss.pl", 
    "EntryId"=>"25"
}

I would like to receive: [["Company Name", "Field6"], ["Email", "Field5"]]

I tried to use scan method but have some problems:

>>  fields = params['FieldStructure'].scan(/Title\":\"(.+?)\".+ID\":\"(.+?)\"/)  
=> [["Company Name", "Field5"]]

How to achieve this?


Solution

  • A non-regex solution:

    require 'json'
    params = {"FieldStructure"=>"{\"Fields\":[{\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},{\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}]}", "Field6"=>"tettetette", "Field5"=>"test@tessss.pl", "EntryId"=>"25"}
    
    a = JSON.parse(params["FieldStructure"])
    out = a["Fields"].map {|a| [a["Title"],a["ID"]]}
    p out  # [["Company Name", "Field6"], ["Email", "Field5"]]