Created
December 13, 2016 08:06
-
-
Save aarti/3ea1b6b0474120fddde87d9b1bb62aee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def deserialize(input) | |
h = {} | |
l = 0 | |
stack = [] | |
curr_string = "" | |
while l < input.length do | |
case input[l] | |
when "{" #state = DICT_START | |
curr_string = "" | |
when ":" #state = VALUE_START | |
stack.push(curr_string) | |
curr_string = "" | |
when "}", "," #state = DICT_END | |
if curr_string != "" then | |
stack.push(curr_string) | |
end | |
if stack.length > 0 then | |
val = stack.pop | |
key = stack.pop | |
stack.push({key => val}) | |
end | |
curr_string = "" | |
else | |
curr_string+=input[l] | |
end | |
l+=1 | |
end | |
stack.each {|n| h.merge!(n)} | |
h | |
end | |
p deserialize("{a:test,b:test1,c:test3}") | |
p deserialize("{a:{b:test1}}") | |
p deserialize("{a:{b:{c:test1}}}") | |
p deserialize("{a:{b:{c:test1}},d:123}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Input: "{a:test,b:test1,c:test3}" #string
Output: {"a"=>"test", "b"=>"test1", "c"=>"test3"} #hash nested to any level
Input: "{a:{b:test1}}"
Output: {"a"=>{"b"=>"test1"}}
Input: "{a:{b:{c:test1}}}"
Output: {"a"=>{"b"=>{"c"=>"test1"}}} #hash nested to any level
Input: "{a:{b:{c:test1}},d:123}"
Output: {"a"=>{"b"=>{"c"=>"test1"}}, "d"=>"123"}