2
嗨,我是在新的紅寶石和我想要一個嵌套的散列保存到一個JSON文件,最終散列看起來是這樣的:紅寶石創建嵌套的哈希值,並將其保存到JSON
{"**School**":{"*Students*":{ "Info":{},"Values":{} },"*Teachers*":{ "Info":{},"Values":{} } } }
但最初的散列必須啓動空:
{"**School**":{} }
然後我需要在各個層面添加元素,像這樣:
{"**School**":{} ,"**Hospital**":{} }
而且
{"**School**":{ "*Students*":{} } ,"**Hospital**":{} }
而且
{"**School**":{ "*Students*":{ "*Info*":{ "Name": "Varchar" },"*Values*":{ "Name": "Jane" } } } ,"**Hospital**":{} }
我試過的東西像下面的一個,但它似乎並沒有工作:
hash = Hash.new
hash[ "**School**" ] = {"Student":{}}
hash[ "**School**" ][ "Student" ] = {"Info":{},"Values":{}}
File.open("saved.json","w") do |f|
f.write(hash.to_json)
感謝您的時間和幫助。
你是什麼意思*似乎不工作*?你有錯誤嗎?意想不到的結果?你的問題是什麼? – spickermann
當我嘗試添加值:「教師」:{}散列 – Jay
....我的代碼剛剛覆蓋「** Teachers **」:{}其中位於「** Student **」:{ }。此外,我的代碼還會重複插入以獲得此結果:{「** School **」:{「Teachers」:{},「** Teachers **」:{「_ Info _」:{},_ Values _「:{} }}} – Jay