在Rails中解析JSON文件:提取值并将值映射到DB模型

时间:2016-02-10 03:11:52

标签: ruby-on-rails json

我有一个JSON文件,其结构如下:

[
  {
    "Name" : {
      "Attribute" : " Value",
      "Attribute2" : " Value2",
      "Attribute3" : " Value3",
    }
   , "Name2" : {
    ...
    }
]

我试图将此文件播种到数据库表中。我不需要所有属性:值对,所以我需要将我需要的那些映射到循环中的create命令。这就是我在seeds.rb文件中尝试的内容:

json = ActiveSupport::JSON.decode(File.read("db/exercises.json"))

json.each_with_index do |e, index|

    Model.create!(
        name: e[0]
        )

end

我基本上需要做的是这样的事情:

Model.create!(
    name: e[0],
    attribute1: e[0][attribute1],
    attribute3: e[0][attribute3]
    )

任何帮助?

1 个答案:

答案 0 :(得分:1)

您的大部分困惑都在于如何访问您的对象。 ActiveSupport::JSON.decode将您的数据解析为包含带有密钥"Name""Name2"等的哈希的数组。Hash#each会产生|key, value|对,您可以使用这些对来填充您的数据数据库。您的密钥变为Model#name,然后您可以将数据的属性映射到您的模型。

data = ActiveSupport::JSON.decode(File.read("db/exercises.json"))
data = data[0] # Unwrap the Array

data.each do |name, attributes|
  Model.create!(
    name: name,
    column_one: attributes['one'],
    column_two: attributes['another one']
  )
end

如果您的文件与列共享密钥名称,Rails会提供Hash#slice以轻松提取子集。

> {a: 1, b: 2, c: 3}.slice(:a, :c)
#=> {a: 1, c: 3}