Created
November 30, 2012 09:52
-
-
Save mmack/4174856 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "awesome_print" | |
def make_hash(keys, value) | |
keys.empty? ? value : { keys.shift => make_hash(keys, value) } | |
end | |
data = { | |
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:message:name" => "max", | |
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:text" => "bla", | |
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:message:line:x" => 123 | |
} | |
@json = {} | |
data.each do |key, value| | |
@json = @json.merge(make_hash(key.split(':'), value)) | |
end | |
ap @json |
Expected:
{
"80e33bc0-1b9a-0130-d2fb-38f6b113e413" => {
"data" => {
"message" => {
"name" => "max"
"line" => {
"x" => 123
}
},
"text" => "bla"
}
}
}
This one works:
require "awesome_print"
def make_hash(keys, value)
keys.empty? ? value : { keys.shift => make_hash(keys, value) }
end
def recurse_merge(a,b)
a.merge(b) do |_,x,y|
(x.is_a?(Hash) && y.is_a?(Hash)) ? recurse_merge(x,y) : [*x,*y]
end
end
data = {
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:message:name" => "max",
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:text" => "bla",
"80e33bc0-1b9a-0130-d2fb-38f6b113e413:data:message:line:x" => 123
}
@json = {}
data.each do |key, value|
single_json = make_hash(key.split(':'), value)
@json = recurse_merge(@json, single_json)
end
ap @json
Disclaimer: All credit goes to the big database of stackoverflow :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: