vishnu vardhan vishnu vardhan - 7 months ago 47
Ruby Question

Need alternative for eval

I have a string

string = '{"a" => [{"b" => 2}]}'

# => {"a" => [{"b" => 2}]}

I need alternative for this to have output like
{"a" => [{"b" => 2}]}

Answer Source

When storing data in strings that will be parsed programmatically, it's best to format those strings using a standardized data-interchange format, such as JSON. Your string, formatted into JSON, would look like this:

{"a": [{"b": 2}]}

If you have any control over how the data is saved in excel, you should make sure it's saved in JSON format like this. If, for some reason, you're not allowed to modify the format of the data in excel, your next best option is to convert it to JSON before parsing it.

Fortunately for you, the data is already very similar to JSON. The only difference is that JSON uses : instead of =>, so you can do this:

require "json"
string = '{"a" => [{"b" => 2}]}'.gsub("=>", ":")
data = JSON.parse string
p data # => {"a" => [{"b" => 2}]}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download