将 JSON 转换为 Ruby 中的 hashmap
transform JSON to hashmap in Ruby
我正在尝试将包含对象和数组的 json 文件转换为 JSON 文件。
下面是 JSON 文件
{
"localbusiness":{
"name": "toto",
"phone": "+11234567890"
},
"date":"05/02/2016",
"time":"5:00pm",
"count":"4",
"userInfo":{
"name": "John Doe",
"phone": "+10987654321",
"email":"john.doe@unknown.com",
"userId":"user1234333"
}
}
我的目标是保存这是一个数据库,例如 MongoId。我想用 map 得到类似的东西:
localbusiness_name => "toto",
localbusiness_phone => "+11234567890",
date => "05/02/2016",
...
userInfo_name => "John Doe"
...
我试过 map 但它没有拆分本地业务或 userInfo 的数组
def format_entry
ps = @params.map do | h |
ps.merge!(h)
@@logger.info("entry #{h}")
end
@@logger.info("formatting the data #{ps}")
ps
end
我真的不知道如何解析每个条目并重建名称
在我看来,您正试图 "flatten" 将内部哈希值合并为一个大哈希值。 Flatten 是不正确的,因为您想将散列的键添加到子散列的键之前。这将需要遍历散列,然后再次遍历每个子散列。此代码示例仅在深度为 1 层时才有效。如果你有多层,那么我建议做两种方法,或者递归方法。
@business = { # This is a hash, not a json blob, but you can take json and call JSON.parse(blob) to turn it into a hash.
"localbusiness":{
"name": "toto",
"phone": "+11234567890"
},
"date":"05/02/2016",
"time":"5:00pm",
"count":"4",
"userInfo":{
"name": "John Doe",
"phone": "+10987654321",
"email":"john.doe@unknown.com",
"userId":"user1234333"
}
}
@squashed_business = Hash.new
@business.each do |k, v|
if v.is_a? Hash
v.each do |key, value|
@squashed_business.merge! (k.to_s + "_" + key.to_s) => value
end
else
@squashed_business.merge! k => v
end
end
我注意到您在枚举散列 @params.each { |h| ... }
时得到 "unexpected" 结果,因为它同时为您提供了键和值。相反,您想像我在上面的代码示例中那样做 @params.each { |key, value| ... }
。
我正在尝试将包含对象和数组的 json 文件转换为 JSON 文件。
下面是 JSON 文件
{
"localbusiness":{
"name": "toto",
"phone": "+11234567890"
},
"date":"05/02/2016",
"time":"5:00pm",
"count":"4",
"userInfo":{
"name": "John Doe",
"phone": "+10987654321",
"email":"john.doe@unknown.com",
"userId":"user1234333"
}
}
我的目标是保存这是一个数据库,例如 MongoId。我想用 map 得到类似的东西:
localbusiness_name => "toto",
localbusiness_phone => "+11234567890",
date => "05/02/2016",
...
userInfo_name => "John Doe"
...
我试过 map 但它没有拆分本地业务或 userInfo 的数组
def format_entry
ps = @params.map do | h |
ps.merge!(h)
@@logger.info("entry #{h}")
end
@@logger.info("formatting the data #{ps}")
ps
end
我真的不知道如何解析每个条目并重建名称
在我看来,您正试图 "flatten" 将内部哈希值合并为一个大哈希值。 Flatten 是不正确的,因为您想将散列的键添加到子散列的键之前。这将需要遍历散列,然后再次遍历每个子散列。此代码示例仅在深度为 1 层时才有效。如果你有多层,那么我建议做两种方法,或者递归方法。
@business = { # This is a hash, not a json blob, but you can take json and call JSON.parse(blob) to turn it into a hash.
"localbusiness":{
"name": "toto",
"phone": "+11234567890"
},
"date":"05/02/2016",
"time":"5:00pm",
"count":"4",
"userInfo":{
"name": "John Doe",
"phone": "+10987654321",
"email":"john.doe@unknown.com",
"userId":"user1234333"
}
}
@squashed_business = Hash.new
@business.each do |k, v|
if v.is_a? Hash
v.each do |key, value|
@squashed_business.merge! (k.to_s + "_" + key.to_s) => value
end
else
@squashed_business.merge! k => v
end
end
我注意到您在枚举散列 @params.each { |h| ... }
时得到 "unexpected" 结果,因为它同时为您提供了键和值。相反,您想像我在上面的代码示例中那样做 @params.each { |key, value| ... }
。