Home > Blockchain >  How to retrieve data from an external nested json file on seed.rb
How to retrieve data from an external nested json file on seed.rb

Time:01-25

I want to retrieve data from an external nested json file on my seed.rb The JSON look like this :

{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}

I saw a solution on github but it only works on non-nested json : https://github.com/liveinsights/clone-monthly-subscriptions/blob/master/db/seeds.rb

CodePudding user response:

Let's say you have JSON file db/seeds.json:

{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}

You can use it like this in your db/seeds.rb:

seeds = JSON.parse(Rails.root.join("db", "seeds.json"), symbolize_names: true)

User.create(seeds[:people])

seeds[:people] in this case is array of hashes with user attributes

CodePudding user response:

if you have:

json_data = {"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}

when you do:

json_data[:people]

you'll get an array:

[{:name=>"John", :age=>"23"}, {:name=>"Jack", :age=>"25"}]

if you want to use this array to populate a model, you can do:

People.create(json_data[:people])

if you want to read each item values, you can iterate through your data, like:

json_data[:people].each {|p| puts p[:name], p[:age]}
  •  Tags:  
  • Related