2014-10-11 109 views
-1

我試圖從一個論壇寫入數據到一個JSON文件。在JSON文件的層次結構應該看起來是這樣的:在Ruby中創建嵌套哈希

thread_id 
    post_id 
     ...some_items... 

或者更具體地說:

{ 
    "0101": { 
     "title": "Hi everybody", 
     "1001": {...}, 
     "1002": {...} 
    }, 
} 

在我的功能相關的部分看起來像這樣:

return { 
    thread_id.to_i => { 
    :title => title, 
    post_id.to_i => {...} 
    } 
} 

結果是每個帖子成爲新父母的孩子thread_id

{ 
    "0101":{ 
     "title":"Hi everybody", 
     "1001":{...} 
    }, 
    "0101":{ 
     "1002":{...} 
    } 
} 

我在做什麼錯?

+4

您能否提供更多的方法?很明顯,你將每篇文章都包裝在一個線程節點中,但爲了幫助你,我們需要知道你如何循環你的數據。 – BroiSatse 2014-10-11 00:49:31

+0

':title => title'或'「title」:「大家好」不適合您聲稱要製作的JSON格式的任何地方。 – sawa 2014-10-11 01:50:02

回答

1

首先,您試圖實現的JSON模式在我看來並不完全正確。看看你的想法呢:

{ 
    "threads": [ 
    { 
     "id": 100, 
     "title": "Lorem ipsum dolor sit amet", 
     ... 
     "posts": [ 
     { 
      "id": 1000, 
      "body": "Lorem ipsum dolor sit amet", 
      ... 
     }, 
     ... 
     ] 
    }, 
    ... 
    ] 
} 

而且回答你的問題取決於如何您的數據起步的,這是我們不知道,所以我會在我的預料中的數據項回答結構看起來像。 (注意:不要使用常量Thread;它已經是一個Ruby類,用於完全不相關的事情)。

class ForumThread 

    def self.serialize(threads) 
    { threads: threads.map(&:serialize) } 
    end 

    def serialize 
    attrs_to_serialize.inject({}) do |hash, attr| 
     hash[attr] = send(attr) 
     hash 
    end 
    end 

    def serialized_posts 
    posts.map &:serialize 
    end 

    def attrs_to_serialize 
    [:id, :title, ..., :serialized_posts] 
    end 

end 

class ForumPost 

    def serialize 
    attrs_to_serialize.inject({}) do |hash, attr| 
     hash[attr] = send(attr) 
     hash 
    end 
    end 

    def attrs_to_serialize 
    # same sort of thing as above 
    # ... 
    end 

end 

# Given the `threads` variable below holds an array or array-like 
# object of ForumThread instances you could do this: 

JSON.generate ForumThread.serialize(threads) # => { "threads": [...] }