Last active
November 29, 2023 14:25
-
-
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
This file contains 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 characters
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) |
Suggestion: Add a regex to handle symbolized keys. This is what I implemented: ruby_hash_text.gsub!(/\b(\w+):/, '"\1" =>')
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
Suggestion : You could add a gsub of all :nil to :null to handle that particular weirdness. – SteveTurczyn