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

江枫思渺然 提交于 2019-12-08 10:12:28

问题


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?


回答1:


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



回答2:


The correct way is:

params['FieldStructure'].scan(/Title\":\"(.+?)\".+?ID\":\"(.+?)\"/)  

Your .+ before ID was greddy, meaning that it would consume the most characters it can until find the next ID. the ? in the end turns it in no greddy.



来源:https://stackoverflow.com/questions/15948128/how-to-scan-single-line-params-string-and-return-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!