On Aug 26, 2013, at 2:42 PM, Love U Ruby <lists@ruby-forum.com> wrote:
> 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?
>
> -
There is no JSON here at all.
Given this:
> new_str = new_str.prepend("{") << "}"
> # => "{1=>2,3=>{4=>5,6=>7}}"
You have a string which represents a what a Hash looks like. Why not run it through eval and see what you get?
my_hash = eval(new_str)
--
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/D83E564F-33DE-4060-B4C5-8E010AE04835%40gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.
No comments:
Post a Comment