2

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Jay
  • 23
  • 4
  • What do you mean by *doesn't seem to work*? Do you get an error? An unexpected result? What is your question? – spickermann May 08 '17 at 06:34
  • Well when I try to add the value: "Teachers":{} to the hash – Jay May 08 '17 at 06:42
  • ....my code just overwrite "**Teachers**":{} where is located "**Student**":{} . And also my code duplicate the insertion getting this result : {"**School**":{"Teachers":{},"**Teachers**":{"_Info_":{},"_Values_":{}}}} – Jay May 08 '17 at 06:49

2 Answers2

2

Your problem is that the key of :

{"Student": {}}
# {:Student=>{}}

is

:Student

and not

"Student"

To define a string key, use:

{"Student" => {}}

to_json doesn't seem to care if the key is a symbol or a string, and exports them both with the same format:

require 'json'
puts ({a: 1, "a" => 2}.to_json)
# {"a":1,"a":2}

This doesn't help for debugging.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

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.

Naveen Krishnan
  • 356
  • 2
  • 6