Skip to content

Instantly share code, notes, and snippets.

@just3ws
Last active December 12, 2023 01:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save just3ws/d002243983ae00886c37 to your computer and use it in GitHub Desktop.
Save just3ws/d002243983ae00886c37 to your computer and use it in GitHub Desktop.
Converting a string representation of a Ruby Hash back into a Ruby Hash
require 'pp'
require 'json'
s = "{:exit_url=>\"null\", :exit_target_type=>\"left\", :furthest_scrolled=>\"locations\", :time_spent=>\"543210\", :user_id=>\"123456\", :visited_at=>789101112, :user=>nil}"
pp JSON.parse("{" + s.gsub(/^{|}$/, '').split(', ').map { |pair| pair.split('=>') }.map {|k, v| [k.gsub(/^:(\w*)/, '"\1"'), v == 'nil' ? "null" : v].join(": ") }.join(", ") + "}")
=> {"exit_url"=>"null", "exit_target_type"=>"left", "furthest_scrolled"=>"locations", "time_spent"=>"543210", "user_id"=>"123456", "visited_at"=>789101112, "user"=>nil}
@just3ws
Copy link
Author

just3ws commented May 5, 2014

I hate this code but it's better than eval. Any suggestions?

@jeremygpeterson
Copy link

jeremygpeterson commented Sep 25, 2020

This is what I found:

def string_parse_to_hash(string)
  modified_string = string
    .gsub(/:(\w+)/){"\"#{$1}\""}
    .gsub('=>', ':')
    .gsub("nil", "null")
  JSON.parse(modified_string)
rescue
  {}
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment