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.

4

2 回答 2

2

你的问题是关键:

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

:Student

并不是

"Student"

要定义字符串键,请使用:

{"Student" => {}}

to_json似乎并不关心键是符号还是字符串,并以相同的格式导出它们:

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

这对调试没有帮助。

于 2017-05-08T08:26:26.307 回答
1

尝试这个...

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

这将使用空内容以所需的结构初始化您的哈希。

于 2017-05-08T07:32:25.793 回答