开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜