Search code examples
jsonrubyruby-hash

Create nested hashes in ruby and save it into JSON


Hi I'm new in ruby and I'm trying to save a nested hash into a JSON file, the final hash looks like this:

{"**School**":{"*Students*":{ "Info":{},"Values":{} },"*Teachers*":{ "Info":{},"Values":{} } } }

But initially the hash must start empty :

{"**School**":{} }

And then I need to add elements at every level , like this :

{"**School**":{} ,"**Hospital**":{} }

And

{"**School**":{ "*Students*":{} } ,"**Hospital**":{} }

And

{"**School**":{ "*Students*":{ "*Info*":{ "Name": "Varchar" },"*Values*":{ "Name": "Jane" } } } ,"**Hospital**":{} }

I tried thing like the one below but it doesn't seem to work :

hash = Hash.new 

hash[ "**School**" ] = {"Student":{}} 

hash[ "**School**" ][ "Student" ] = {"Info":{},"Values":{}}


File.open("saved.json","w") do |f|

f.write(hash.to_json)

Thanks for your time and help.


Solution

  • Try this...

    hash = Hash.new
    hash[ "**School**" ] = {}
    hash[ "**School**" ][ "Student" ] = {}
    hash[ "**School**" ][ "Student" ]["Info"] = {}
    hash[ "**School**" ][ "Student" ]["Values"] = {}
    

    This will initialise your hash in desired structure with empty content.