简体   繁体   中英

Parse nested JSON and save it to the database with rails

Using rails (4), I would like to parse some data from an external API and store it into my database. For instance:

{ "name" : "Mercedes-Benz",
  "commonName: "Mercedes",
  "vehicles" : [ {
    "name" :  "Mercedes c5",
    "components" : ["wheels", "doors"]
  }]
}

I am aware that with JSON.parse I could create a new instance and store it if the json would match, but there are a few problems that prevent me to do it:

  • commonName uses cammelcase instead of rails typical underscore. Is there a way i can magically assign a key to an attribute?

  • Will vehicles be saved to the table vehicles ? Can I accomplish that automatically? Or should I go through every vehicle and save each one?

  • Components is just an array of strings. What would be a good way to represent that? Just another table with an attribute name ?

Yes, if you want to be able to look up the components then having it as a separate table makes sense. It would need a vehicle_id as well as name .

For accepting the attributes for the vehicles and components use accepts_nested_attributes_for .

So your models should looked something like this:

class VehicleType < ActiveRecord::Base
  has_many :vehicles

  accepts_nested_attributes_for :vehicles
end

class Vehicle < ActiveRecord::Base
  belongs_to :vehicle_type      
  has_many :components

  accepts_nested_attributes_for :components
end

class Component < ActiveRecord::Base
  belongs_to :vehicle
end

For converting commonName (camelCase) to common_name (snake case), there's a great Stack Overflow answer on that here: Converting nested hash keys from CamelCase to snake_case in Ruby . So assuming you have defined the function described there ( convert_hash_keys ) and the models above, your code should look roughly like this:

converted_hash = convert_hash_keys(JSON.parse(input_json_string))
vehicle_type = VehicleType.create(converted_hash)

For updating it would be VehicleType.update(converted_hash)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM