Ciao, sono nuovo in ruby e sto cercando di salvare un hash annidato in un file JSON, l'hash finale è simile a questo:
{"**School**":{"*Students*":{ "Info":{},"Values":{} },"*Teachers*":{ "Info":{},"Values":{} } } }
Ma inizialmente l'hash deve iniziare vuoto:
{"**School**":{} }
E poi ho bisogno di aggiungere elementi ad ogni livello, in questo modo:
{"**School**":{} ,"**Hospital**":{} }
E
{"**School**":{ "*Students*":{} } ,"**Hospital**":{} }
E
{"**School**":{ "*Students*":{ "*Info*":{ "Name": "Varchar" },"*Values*":{ "Name": "Jane" } } } ,"**Hospital**":{} }
Ho provato una cosa come quella qui sotto ma non sembra funzionare:
hash = Hash.new
hash[ "**School**" ] = {"Student":{}}
hash[ "**School**" ][ "Student" ] = {"Info":{},"Values":{}}
File.open("saved.json","w") do |f|
f.write(hash.to_json)
Grazie per il tuo tempo e aiuto.
risposte:
1 per risposta № 1Prova questo...
hash = Hash.new
hash[ "**School**" ] = {}
hash[ "**School**" ][ "Student" ] = {}
hash[ "**School**" ][ "Student" ]["Info"] = {}
hash[ "**School**" ][ "Student" ]["Values"] = {}
Questo inizializzerà il tuo hash nella struttura desiderata con contenuto vuoto.
2 per risposta № 2
Il tuo problema è che la chiave di:
{"Student": {}}
# {:Student=>{}}
è
:Student
e non
"Student"
Per definire una chiave di stringa, utilizzare:
{"Student" => {}}
to_json
non sembra preoccuparsi se la chiave è un simbolo o una stringa e li esporta entrambi con lo stesso formato:
require "json"
puts ({a: 1, "a" => 2}.to_json)
# {"a":1,"a":2}
Questo non aiuta per il debug.