简体   繁体   中英

convert request parameter of array hashes to ruby hashes

I have the following 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"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM