在Ruby中创建嵌套哈希
问题描述:
我试图从一个论坛写入数据到一个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":{...}
}
}
我在做什么错?
答
首先,您试图实现的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": [...] }
您能否提供更多的方法?很明显,你将每篇文章都包装在一个线程节点中,但为了帮助你,我们需要知道你如何循环你的数据。 – BroiSatse 2014-10-11 00:49:31
':title => title'或'“title”:“大家好”不适合您声称要制作的JSON格式的任何地方。 – sawa 2014-10-11 01:50:02