convert request parameter of array hashes to ruby hashes
I have the fo开发者_如何学Cllowing request parameters:
"mappings"=>"[{ \"spec_id\" => \"1\",
\"item_name\" => \"sku\"}|{ \"spec_id\" => \"2\",
\"item_name\" => \" productname\"}|{ \"spec_id\" => \"4\",
\"item_name\" => \" price\"}]"
I'd like to know how I can parse the items in hashes.
The first thing I do is
mappings = params[:mapping][:mappings].split("|")
mappings.each do |map|
# don't know how to create the hashes
end
I would prefer to split on "," instead of "|" if possible and I'm not 100% sure if the request parameter are in the correct format. If it isn't please let me know and I will change it.
To parse this string, I would do the following:
str = "[{ \"spec_id\" => \"1\",
\"item_name\" => \"sku\"}|{ \"spec_id\" => \"2\",
\"item_name\" => \" productname\"}|{ \"spec_id\" => \"4\",
\"item_name\" => \" price\"}]"
mappings = JSON.parse(str.gsub(/}\s*\|\s*{/, '},{').gsub(/\s*\=\>/, ':'))
This will basically convert what you have into a JSON string by removing the '|' characters and converting the '=>' into ':'. When you finally parse the result you'll be parsing JSON, so you'll get a nice Ruby Hash:
[{"spec_id"=>"1", "item_name"=>"sku"}, {"spec_id"=>"2", "item_name"=>" productname"}, {"spec_id"=>"4", "item_name"=>" price"}]
精彩评论