Skip to content

Instantly share code, notes, and snippets.

@dvdantunes
Last active August 14, 2019 16:21
Show Gist options
  • Select an option

  • Save dvdantunes/2563227424fd69b7c0ee5b3719954ea4 to your computer and use it in GitHub Desktop.

Select an option

Save dvdantunes/2563227424fd69b7c0ee5b3719954ea4 to your computer and use it in GitHub Desktop.

Revisions

  1. dvdantunes revised this gist Aug 14, 2019. No changes.
  2. dvdantunes created this gist Aug 14, 2019.
    32 changes: 32 additions & 0 deletions hash_string_to_json.rb
    Original 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