【问题标题】:Map object and nested object to model using Ruby on Rails使用 Ruby on Rails 将对象和嵌套对象映射到模型
【发布时间】:2013-05-09 19:26:55
【问题描述】:

我有一个像

这样的对象
{"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 上进行了搜索,但找不到任何东西,正确的方法是什么?我应该将嵌套对象移到上面的对象吗?我不需要它嵌套...

提前致谢

【问题讨论】:

  • 基于上面的json,你可以发送多个链接(它是一个数组)。在这种情况下,你想做什么?
  • 由于某种原因,json 来自的 API 从不提供多个链接,只是提供多个结果

标签: ruby-on-rails json activerecord


【解决方案1】:

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

我在下面假装你的 json 在一个名为 input.json 的文件中——但你显然只是解析文本或使用现有的 JSON 对象

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

这会创建对象:

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

【讨论】:

  • 我想要所有的数据,所以也许最好像 {"Result":[{ "UrlTo":"example.com", "Visited":1364927598, "FirstSeen" :1352031217, "PrevVisited":1362627231, "Anchor":"example.com", "Type":"Text", "Flag":[], "TextPre":"", "TextPost":"", "Index ":0, "Rating":0.001416, "UrlFrom":"exampletwo.com", "IpFrom":"112.213.89.105", "Title":"示例标题", "LinksInternal":91, "LinksExternal":51 , "Size":5735 }]} 并将数组移动到上面的数组中?
  • 您需要将其展平为一个简单的哈希,或者有两个对象(结果带有一个链接子项),或者存储 JSON 而不是列。这完全取决于您希望如何存储数据。你应该从那里开始。
  • @MaxRose-Collins 当然——如果您觉得我帮助了您,请将其标记为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2018-10-31
相关资源
最近更新 更多