我正在尝试创建一个深度为N的JSON或Hash。示例:X个名字独特的人可能有Y个孩子,而这些孩子可能有Z个孩子(一直延续到N代(。我想创建一个散列(或JSON(,看起来像这样:
{
"John" => {
"Lara" => {
"Niko" => "Doe"
},
"Kobe" => "Doe"
},
"Jess" => {
"Alex" => "Patrik"
}
}
我尝试过使用递归别名,但没能做到。
alias Person = Hash(String, Person) | Hash(String, String)
输入可以来自类似字符串的数组
["John|Lara|Niko", "John|Kobe", "Jess|Alex"]
["Doe", "Patrik"]
(我可以处理循环。我的问题是将它们添加到哈希中,因为它们的大小未知。(
我偶然发现了这个讨论https://forum.crystal-lang.org/t/how-do-i-create-a-nested-hash-type/885但不幸的是,我无法实现我想要的,也无法保留Hash(或JSON(方法(这是必需的(。
我不太清楚你是如何从示例输入中得到示例结果的,所以我将使用不同的设置:假设我们有一个简单的配置文件格式,其中键是结构化的,并通过点序列分组,所有值都是字符串。
app.name = test
app.mail.enable = true
app.mail.host = mail.local
server.host = localhost
server.port = 3000
log_level = debug
我们可以将其解析为递归Hash
,如下所示:
alias ParsedConfig = Hash(String, ParsedConfig)|String
config = Hash(String, ParsedConfig).new
# CONFIG being our input from above
CONFIG.each_line do |entry|
keys, value = entry.split(" = ")
keys = keys.split(".")
current = config
keys[0..-2].each do |key|
if current.has_key?(key)
item = current[key]
if item.is_a?(Hash)
current = item
else
raise "Malformed config"
end
else
item = Hash(String, ParsedConfig).new
current[key] = item
current = item
end
end
current[keys.last] = value
end
pp! config
输出为:
config # => {"app" =>
{"name" => "test", "mail" => {"enable" => "true", "host" => "mail.local"}},
"server" => {"host" => "localhost", "port" => "3000"},
"log_level" => "debug"}
或者,我们可以将其解析为递归结构:
record ConfigGroup, entries = Hash(String, ConfigGroup|String).new
config = ConfigGroup.new
# CONFIG being our input from above
CONFIG.each_line do |entry|
keys, value = entry.split(" = ")
keys = keys.split(".")
current = config
keys[0..-2].each do |key|
if current.entries.has_key?(key)
item = current.entries[key]
if item.is_a?(ConfigGroup)
current = item
else
raise "Malformed config"
end
else
item = ConfigGroup.new
current.entries[key] = item
current = item
end
end
current.entries[keys.last] = value
end
pp! config
然后输出为:
config # => ConfigGroup(
@entries=
{"app" =>
ConfigGroup(
@entries=
{"name" => "test",
"mail" =>
ConfigGroup(@entries={"enable" => "true", "host" => "mail.local"})}),
"server" => ConfigGroup(@entries={"host" => "localhost", "port" => "3000"}),
"log_level" => "debug"})
递归结构目前没有那么bug,它为解析的域对象上的自定义方法提供了一个很好的位置,并且通常比递归别名有更确定的未来,递归别名有时有点bug。
carc.in的完整示例:https://carc.in/#/r/9mxr