Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested JSON in to active record

Through an API I am getting the JSON response below with a listing of servers.

Since this has nested JSON data what is the best way to create a model and store this data?

All I want to do with this data is store it(for now). Dont care if ipaddresses or lb_applications are flattened, there will never be more than 1 listed.

{"ips"=>[{"address"=>"127.9.34.6"}],
  "memory"=>8589934592,
  "id"=>"79ahvoahvo9h8apdjaidfjeijowfj",
  "storage"=>107374182400,
  "location_id"=>"hdfajhlnf4jaf23wf3f33fwoifjsijfsij",
  "hostname"=>"my.server.name.com",
  "description"=>"8 GB RAM + 100 GB Disk",
  "cpu"=>4.0,
  "status"=>"running",
  "lb_applications"=>
   [{"lb_application_name"=>"Staging",
     "lb_application_id"=>"2ohuro2lufp92epf9dpe0ijpdijfps9udhfp9"}]},
 {"ips"=>[{"address"=>"127.99.6.75"}],
  "memory"=>4294967296,
  "id"=>"ufho923ehufp9idf0i3jef0ijd32ddd2",
  "storage"=>53687091200,
  "location_id"=>"93fj8j93jf9hj39fh93h9g3hrg9",
  "hostname"=>"my.server2.name.com",
  "description"=>"",
  "cpu"=>2.0,
  "status"=>"running",
  "lb_applications"=>[]},
like image 300
pablo Avatar asked Jan 27 '26 16:01

pablo


1 Answers

You could always serialize the hash, and then store any extra columns from the data that you might need to query.

In your migration, you'll add the field like its text.

add_column :my_models, :my_hash, :text, :limit => 16000000 #only add the limit bit if the hash is exceptionally long
add_column :my_models, :other_data, :string

at the top of your model you should have:

class MyModel < ActiveRecord::Base
  serialize :my_hash, Hash

and then all you have to do when creating your model is this:

hash = {:rawr => "Lion"}
MyModel.create(:my_hash=>hash, :other_data=>hash[:rawr])
like image 112
BananaNeil Avatar answered Jan 29 '26 06:01

BananaNeil