2016-04-28 61 views
2

我正在嘗試閱讀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" 
     } 
    } 
} 

回答

1

這應該解決您的問題:

def loop_params(schema) 
    new_parent = Hash.new 

    schema["fields"].each do |field| 
    new_key = field["key"] 

    if !field["group"].nil? && field["object"].nil? 
     new_parent[new_key] = parse_config(field) 
    else 
     new_parent[new_key] = loop_params(field) 
    end 
    end 

    new_parent 
end 

有代碼中的一些問題,可能會導致錯誤。使用@來聲明一個變量使其成爲一個實例變量,這意味着它的值將在函數完成後保持。由於我們無法看到程序的其餘部分,我不知道是否需要全部或部分程序,但是我沒有寫出我的解決方案。

其他一些注意事項:

if fields["object"].nil? & !fields["group"].nil? 

您的&使用實際上是位運算符and,而不是條件and。改爲使用&&

另外,如果你使用puts代替printputs會自動追加一個"\n"對你來說,這是一個很好的方便記住。

+0

您的解決方案就像一個魅力。並感謝您提供有關我向您展示的代碼片段的提示,我將在處理其他應用時考慮這些提示。 –