合并两个json文件并对其进行迭代

问题描述

我的Rails根目录中有两个json文件(info.json和images.json)。它们都是我拥有的以及我一直在使用Mechanize Gem进行的Web剪贴项目中的摘录。

所以我有两个Json文件,其中一个具有有关Plants的信息,如下所示:

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国家/地区信息相同。我想知道如何合并两个文件并将它们保存在数据库中

解决方法

以下应能工作:

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...