Last active
August 14, 2019 16:21
-
-
Save dvdantunes/2563227424fd69b7c0ee5b3719954ea4 to your computer and use it in GitHub Desktop.
Revisions
-
dvdantunes revised this gist
Aug 14, 2019 . No changes.There are no files selected for viewing
-
dvdantunes created this gist
Aug 14, 2019 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,32 @@ # 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