我正在嘗試閱讀JSON模式,解析特定內容並使用相同的嵌套結構生成新的散列。閱讀嵌套散列並生成類似結構的單獨散列
但是我能夠遍歷原始模式,然後當我嘗試創建新的嵌套哈希時,它變平了。
這是我到目前爲止有:
require 'json'
@schema = JSON.parse("{
"fields": [
{
"group": "common",
"key": "1st_level"
},
{
"object": "nested",
"key": "order",
"fields": [
{
"group": "common",
"key": "2nd_level_1"
},
{
"object": "nested",
"key": "order2",
"fields": [
{
"group": "common",
"key": "3rd_level_1"
}
]
}
]
}
]
}
")
@event_output = Hash.new
def parse_config(fields)
if fields["group"].downcase == "common"
@response = "HIT HERE"
else
@response = "INVALID GROUP"
end
return @response
end
def loop_params(parent, key, schema)
@new_output = Hash.new
@parent = parent
schema["fields"].each do |fields|
if fields["object"].nil? & !fields["group"].nil?
@key = fields["key"]
@repsonse = parse_config(fields)
@new_output[@key] = @repsonse
if key != ""
@parent[key] = @new_output
else
@parent = @new_output
end
else
print @parent
@key = fields["key"]
loop_params(@parent, @key, fields)
end
end
return @parent
end
@event_output = loop_params(@event_output, "", @schema)
print "\n FINAL OUTPUT \n"
print @event_output
從這個輸出是:
{
"1st_level"=>"HIT HERE",
"order"=>{
"2nd_level_1"=>"HIT HERE"
},
"order2"=>{
"3rd_level_1"=>"HIT HERE"
}
}
這是接近,但我想:
{
"1st_level"=>"HIT HERE",
"order"=>{
"2nd_level_1"=>"HIT HERE",
"order2"=>{
"3rd_level_1"=>"HIT HERE"
}
}
}
您的解決方案就像一個魅力。並感謝您提供有關我向您展示的代碼片段的提示,我將在處理其他應用時考慮這些提示。 –