问题
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