1

I stored my nested hash in a file, and while retrieving it, I want to it back in a hash form instead of string. When I read a file it will give me a string and then how can I parse it back to a hash. This is the string hash in the file:

{"SONGS"=>{1=>["2018-05-29 18:19:14 +0530", "HAPPY", "Meri Sapnon Ki Rani"]}}
Salman Shaik
  • 15
  • 1
  • 7

1 Answers1

0

Already in SO.

WARNING SECURITY RISK!

For your string you need to pass to eval, but this is a SECURITY RISK

string = '{"SONGS"=>{1=>["2018-05-29 18:19:14 +0530", "HAPPY", "Meri Sapnon Ki Rani"]}}'
p eval(string).class

If you need to store data structures in files, I suggest you to take a look at YAML module. Look at this post, for example.

As suggested in comments:

  • Consider also security concerns, look this post.
  • Consider to change a little bit the string syntax to use a JSON structure. See below.

Use of JSON:

require 'json'
json_string = '{"songs":{"1":{"date": "2018-05-29 18:19:14 +0530", "title":"HAPPY", "name":"Meri Sapnon Ki Rani"}}}'
p JSON::parse(json_string).class
iGian
  • 11,023
  • 3
  • 21
  • 36