0

我有一个像

{"Result":[{
    "Links":[{
            "UrlTo":"http://www.example.com/",
            "Visited":1364927598,
            "FirstSeen":1352031217,
            "PrevVisited":1362627231,
            "Anchor":"example.com",
            "Type":"Text",
            "Flag":[],
            "TextPre":"",
            "TextPost":""
        }],
    "Index":0,
    "Rating":0.001416,
    "UrlFrom":"http://www.exampletwo.com",
    "IpFrom":"112.213.89.105",
    "Title":"Example title",
    "LinksInternal":91,
    "LinksExternal":51,
    "Size":5735
}]}

我有一个带有所有键的模型。

UrlTo, Visited, FirstSeen, PrevVisited, Anchor, Type, TextPre, TextPost, Index, Rating, UrlFrom, IpFrom, Title, LinksInternal, LinksExternal, Size

我了解如何在没有以下内容的情况下将其保存到数据库中...

"Links":[{
            "UrlTo":"http://example.com/",
            "Visited":1364927598,
            "FirstSeen":1352031217,
            "PrevVisited":1362627231,
            "Anchor":"example.com",
            "Type":"Text",
            "Flag":[],
            "TextPre":"",
            "TextPost":""
        }],

不知道如何用嵌套对象保存它。

我在 Google 和 SO 上进行了搜索,但找不到任何东西,这样做的正确方法是什么?我应该将嵌套对象移到上面的对象吗?我不需要它嵌套......

提前致谢

4

1 回答 1

0

看起来你想保存链接,所以我会遍历提供的 json 中的结果/链接,并根据链接创建一个新的哈希。

I've pretended below that your json is in a file called input.json -- but you'd obviously just parse the text or use an existing JSON object

require 'json'
json = JSON.parse File.read("input.json")

links = json["Result"].map do |result|
  result["Links"].map {|link| link }
end.flatten

hash = {"Links" => links}
puts hash

This creates the object:

{"Links"=>[{"UrlTo"=>"http://www.example.com/", "Visited"=>1364927598, "FirstSeen"=>1352031217, "PrevVisited"=>1362627231, "Anchor"=>"example.com", "Type"=>"Text", "Flag"=>[], "TextPre"=>"", "TextPost"=>""}]}
于 2013-05-09T21:12:05.910 回答