Skip to content

Instantly share code, notes, and snippets.

@dvdantunes
Last active August 14, 2019 16:21
Show Gist options
  • Save dvdantunes/2563227424fd69b7c0ee5b3719954ea4 to your computer and use it in GitHub Desktop.
Save dvdantunes/2563227424fd69b7c0ee5b3719954ea4 to your computer and use it in GitHub Desktop.
hash string to json
# Convert a hash string (a hash that was casted to string using .to_s)
# to a valid json string
#
# @param [String|Hash] hash_string Hash string to parse
# @param [Boolean] prettyfy_for_html [Optional] True if json is wanted to be prettified for HTML output
#
# @return [String]
def hash_string_to_json(hash_string, prettyfy_for_html = true)
# Check if it is already a valid JSON
begin
if hash_string.is_a? String && JSON.parse(hash_string)
return hash_string unless prettyfy_for_html
return JSON.pretty_generate(JSON.parse(hash_string))
end
rescue
end
# Actually parse it
begin
# Hash string keys can have this 2 syntaxes:
# {:hi=>2} -> uses symbols as key
# {\"hi\"=>2} -> uses strings as key
h = JSON.parse(hash_string.gsub(/([\"]?[:]?(\w+)[\"]*\s?=>\s?)/, "\"\\2\": "))
rescue
h = hash_string.is_a?(Hash) ? hash_string : Hash.new
end
return h.to_json unless prettyfy_for_html
JSON.pretty_generate(h)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment