Last active
December 28, 2022 09:55
-
-
Save akagr/0339fb80f1b268a48a43ffbd1606cb3b 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
# Just a copy of https://stackoverflow.com/a/30724359/1825727 | |
def from_hashstring(value) | |
json_string = value | |
.gsub(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>') # Handle ruby symbols as keys | |
.gsub(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>') # Handle numbers as keys | |
.gsub(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"') # Handle symbols as values | |
.gsub(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"') # Handle symbols in arrays | |
.gsub(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:') # Finally, convert => to : | |
JSON.parse(json_string) | |
rescue | |
value | |
end | |
# Test cases for more explanation | |
test 'from_hashstring works on basic ruby hash' do | |
string = '{"url"=>"TEST.png", "type"=>"image/png", "height"=>512}' | |
hash = from_hashstring string | |
assert_equal Hash, hash.class | |
assert_equal 'image/png', hash['type'] | |
assert_equal 512, hash['height'] | |
assert_equal 'abc', from_hashstring('abc') | |
end | |
test 'from_hashstring works on symbols' do | |
string = '{:url => 123}' | |
assert_equal 123, from_hashstring(string)['url'] | |
end | |
test 'from_hashstring works on numeric keys' do | |
string = '{0 => 123}' | |
assert_equal 123, from_hashstring(string)['0'] | |
end | |
test 'from_hashstring works on symbol values' do | |
string = '{"abc" => :test}' | |
assert_equal 'test', from_hashstring(string)['abc'] | |
end | |
test 'from_hashstring works on array of symbols' do | |
string = '{"abc" => [:test, 1, "abc"]}' | |
assert_equal ['test', 1, 'abc'], from_hashstring(string)['abc'] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment