Ruby on Rails Monday, August 26, 2013

require 'json'

str = "1=2,3=(4=5,6=7)"
new_str = str.gsub(/=|\(|\)/) do |m|
if m == "="
m= "=>"
elsif m == "("
m = "{"
else
m = "}"
end
end

new_str = new_str.prepend("{") << "}"
# => "{1=>2,3=>{4=>5,6=>7}}"

JSON.parse(new_str)
# ~>
/home/kirti/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/json/common.rb:155:in
`parse': 757: unexpected token at '{1=>2,3=>{4=>5,6=>7}}'
(JSON::ParserError)
# ~> from
/home/kirti/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/json/common.rb:155:in
`parse'
# ~> from -:15:in `<main>'


My question is how should I get the hash {1=>2,3=>{4=>5,6=>7}} from that
string?

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/da8a33c74e789b2ef9d42b0da3aa5c6b%40ruby-forum.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment