Skip to content

Instantly share code, notes, and snippets.

@gene1wood
Last active November 29, 2023 14:25
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gene1wood/bd8159ad90b0799d9436 to your computer and use it in GitHub Desktop.
Save gene1wood/bd8159ad90b0799d9436 to your computer and use it in GitHub Desktop.
A set of regex converstions to turn a ruby hash output string into a json parseable string
require 'json'
# Example ruby hash string which exercises all of the permutations of position and type
# See http://json.org/
ruby_hash_text='{"alpha"=>{"first second > third"=>"first second > third", "after comma > foo"=>:symbolvalue, "another after comma > foo"=>10}, "bravo"=>{:symbol=>:symbolvalue, :aftercomma=>10, :anotheraftercomma=>"first second > third"}, "charlie"=>{1=>10, 2=>"first second > third", 3=>:symbolvalue}, "delta"=>["first second > third", "after comma > foo"], "echo"=>[:symbol, :aftercomma], "foxtrot"=>[1, 2]}'
puts ruby_hash_text
# Transform object string symbols to quoted strings
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')
# Transform object string numbers to quoted strings
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')
# Transform object value symbols to quotes strings
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')
# Transform array value symbols to quotes strings
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')
# Transform object string object value delimiter to colon delimiter
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')
puts ruby_hash_text
puts JSON.parse(ruby_hash_text)
@gene1wood
Copy link
Author

Suggestion : You could add a gsub of all :nil to :null to handle that particular weirdness. – SteveTurczyn

@mindtonic
Copy link

Suggestion: Add a regex to handle symbolized keys. This is what I implemented: ruby_hash_text.gsub!(/\b(\w+):/, '"\1" =>')

@rafael-angonese
Copy link

Transform nil to "nil"
ruby_hash_text.gsub!(/nil/, '"nil"')

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