使用可以使用軌道serialize
選項
#Model
class MyJsonClass < ActiveRecord::Base
serialize :json_data, Array
end
#migration
create_table :my_json_class do |t|
t.string :json_data
end
#How to save object
data = [
{
"id": "1005",
"name": "UEFA Champions League",
"region": "International"
},
{
"id": "1007",
"name": "UEFA Europa League",
"region": "International"
},
]
object = MyJsonClass.create(json_data: data)
object.json_data #[
# {
# "id": "1005",
# "name": "UEFA Champions League",
# "region": "International"
# },
# {
# "id": "1007",
# "name": "UEFA Europa League",
# "region": "International"
# },
#]
serialize
本身將執行的操作和數據類型轉換爲字符串,同時保存到數據庫中,反之亦然,而取數據庫DB
您可以簡單地對您的執行所有數組操作,並再次將其保存到數據庫
選擇,如果你想存儲的每個記錄sepeartely
#Logic to iterate on json data
data = [
{
"id": "1005",
"name": "UEFA Champions League",
"region": "International"
},
{
"id": "1007",
"name": "UEFA Europa League",
"region": "International"
},
]
data.each do |record|
MyJsonClass.create(record_id: record['id'], name: record['name'], region: record['region'])
end
#migration
create_table :my_json_class do |t|
t.string :name
t.string :region
t.integer :record_id
t.timestamps null: false
end
要想從API調用數據
require 'net/http'
class ApiData
def response
@response ||= http.request(request)
end
private def uri
URI("#{ host }")
end
private def host
'http://api.football-api.com'
end
private def request
request = Net::HTTP::Get.new(url)
request.content_type = 'application/json'
request
end
private def url
"/2.0/competitions?Authorizations=#{authorization_token}"
end
private def authorization_token
put your authorization_token here
end
private def http
@http ||= Net::HTTP.new(uri.host, uri.port)
@http
end
end
ApiData.new.response
AND?你有什麼嘗試?什麼工作?什麼不起作用? –
我從外部API獲取了JSON數據,並且想將這些數據保存到MySQL數據庫中。 –