我正在尝试创建一个可以有N个深度的JSON或Hash。例如:X个名字独特的人可能有Y个孩子,而这些孩子可能有Z个孩子(一直持续到第N代)。我想创建一个Hash (或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"](我可以处理循环。我的问题是将它们添加到Hash中,因为它们的大小未知。)
我遇到了这样的讨论,https://forum.crystal-lang.org/t/how-do-i-create-a-nested-hash-type/885,但不幸的是,我不能实现我想要的,也不能保留Hash的(或JSON的)方法(这是必要的)。
发布于 2020-09-04 18:12:55
我不太明白您是如何从示例输入中得出示例结果的,所以我将使用一个不同的设置:假设我们有一个简单的配置文件格式,其中键是结构化的,并通过点分序列进行分组,所有值都是字符串。
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"})递归结构目前没有那么多buggy,为解析的域对象上的自定义方法提供了一个很好的位置,并且通常比递归别名更有前途,递归别名有时会有一点buggy。
Carc.in上的完整示例:https://carc.in/#/r/9mxr
https://stackoverflow.com/questions/63733240
复制相似问题