【问题标题】:Combine two json files and iterate over them合并两个 json 文件并遍历它们
【发布时间】:2020-08-31 07:50:09
【问题描述】:

我的 Rails 根目录中有两个 json 文件(info.json 和 images.json)。它们都是从我拥有的网络抓取项目中提取的,并且我一直在使用 Mechanize Gem。

所以我有两个 Json 文件,其中一个包含有关植物的信息,如下所示:

info.json

{
  "Brazil":[
  {"Jungle Plants":[bla bla bla ]},
  {"Desert Plants":[ bla bla bla ]}],

  "Egypt":[
  {"Jungle Plants":[bla bla bla ]},
  {"Desert Plants":[ bla bla bla ]}]
  
  and so on...
}

而另一个 Json 文件有这样的国家标志图像:

images.json

{
   "images":
      {
        "Brazil":"link/to/flag_image.jpg", 
        "Egypt":"link/to/flag_image.jpg",
        
         and so on...
      }
}

我的迁移表:

class CreatePlants < ActiveRecord::Migration[5.2]
  def change
    create_table :plants do |t|
      t.string :country_name
      t.jsonb :plant_categories
      t.string :flag_photo

      t.timestamps
    end
  end
end

我目前拥有的:

json_file = File.open("#{Rails.root}/info.json").read
json_objects = JSON.parse(json_file).symbolize_keys

json_objects.each { |key, value| Plants.create!(country_name: key, plant_categories: value) }

在我的种子中,我如何组合这两个 JSON 文件并使它们与各自的图像标志及其数据配对/匹配并将它们保存在数据库中? 我会感谢你的帮助!

编辑:国旗图像的下载顺序与 info.json 国家信息的顺序相同。我想知道如何合并这两个文件并将它们保存在数据库中

【问题讨论】:

    标签: ruby-on-rails json ruby rails-api


    【解决方案1】:

    以下应该可以工作:

    info = JSON.parse(File.read("#{Rails.root}/info.json"))
    images = JSON.parse(File.read("#{Rails.root}/images.json"))
    
    
    info.each do |country_name, plants|
      # Hope the Model name is singular here
      plant = Plant.new(country_name: country_name, plant_categories: plants)
      path = images['images'][country_name]
      if path
        # Read the file from remote URL like S3
        # images['images'][country_name] - Will return the image URL on the key country_name
        attachment = open(images['images'][country_name])
        plant.flag_photo = attachment
      end
      plant.save!
    end
    

    【讨论】:

    • 当我运行种子时,我得到:NoMethodError: undefined method []' for nil:NilClass `知道为什么吗?
    • 能否分享异常的回溯
    • 你是不是像file = open(images[:images][country_name])一样在file = open(images['images'][country_name])线上使用符号作为键?
    • 好的,是的,我错过了那部分 - 现在当我运行迁移时,我得到:TypeError: no implicit conversion of nil into String /Users/thekid/Documents/plants_api/db/seeds.rb:13:in block in &lt;top (required)&gt;' /Users/thekid/Documents/plants_api/db/seeds.rb:10:in each' /Users/thekid/Documents/plants_api/db/seeds.rb:10:in &lt;top (required)&gt;'
    • images.json 上某个国家/地区的文件 URL 是否有可能为空?
    猜你喜欢
    • 2016-08-29
    • 2019-08-10
    • 1970-01-01
    • 2019-09-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多