简体   繁体   中英

Reconstructing a Hash, naming and replacing issue

I'm receiving a string-based Hash looking like the following:

"data"=>{"uno"=>"alfa", "dos"=>"beta"}

I want to reconstruct it, such that it has the following object structure and naming :

beta: {uno: "alfa"}

I'm getting stuck already at taking an inner value and converting it to a key. Any help to reach the above would be much appreciated.

Update
There are several things going on here and I regret doing one question out of it. But now as it's already out in the wild, I'll try my best to explain further.
1. The keys need to be converted to symbols
2. The pair "dos"=>"beta" should be inverted
3. The inverted key of the above mentioned pair should take over the role (from "data" ) as key for the whole Hash

Ps. As I seem to have massively failed in clearly explaining my question, feel free to downvote.

Try the code:

h.reduce({}) { |hh,v| hh[ v[1][ 'dos' ].to_sym ] = { :uno => v[1][ 'uno' ] } ; hh }
# => {:beta=>{:uno=>"alfa"}} 

If you just want to convert the key from string to symbol, use :

hash.inject({}){|h,(k,v)| h[k.to_sym] = v; h}

Doing so will return : {data: {uno: "alfa", dos: "beta"}}

You may want to try this:

The simple way convert to a Ruby hash would be to eval the string, BUT that is dangerous . So we can use a safer way:

>> s = '"data"=>{"uno"=>"alfa", "dos"=>"beta"}'
=> ""data"=>{"uno"=>"alfa", "dos"=>"beta"}"

>> require 'json'
=> true

>> t2 = "{#{s}}".gsub('=>', ':')
=> "{"data":{"uno":"alfa", "dos":"beta"}}"

>> h1 = JSON.parse(t2).to_hash
=> {"data"=>{"uno"=>"alfa", "dos"=>"beta"}}

>> {:data => h1["data"].inject({}){|h,(k,v)| h[k.to_sym] = v; h}}
=> {:data=>{:uno=>"alfa", :dos=>"beta"}}

Also it would be better if you give some more examples of what behaviour you expect.

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