2017-09-18 93 views
-1

我想要從外部JSON鏈接獲取數據並將數據保存到數據庫中。我得到了JSON如下。我想將JSON數據保存到數據庫中

[ 
    { 
    "id": "1005", 
    "name": "UEFA Champions League", 
    "region": "International" 
    }, 
    { 
    "id": "1007", 
    "name": "UEFA Europa League", 
    "region": "International" 
    }, 
] 

實際上我想單獨保存數據。

ID | NAME     | Region  | 
1005 | UEFA Champions League | International | 
1007 | UEFA Europa League | International | 
+0

AND?你有什麼嘗試?什麼工作?什麼不起作用? –

+0

我從外部API獲取了JSON數據,並且想將這些數據保存到MySQL數據庫中。 –

回答

1

使用可以使用軌道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 
+0

我可以通過data =「www.xyx.com」嗎? –

+0

其實,我想分別保存身份證,姓名,地區。所以我怎麼能 –

+0

看到更新的答案 –

0

什麼是你的數據庫如果您使用的是postgres,則支持將該列聲明爲json列。\

遷移是:

add_column :pages, :config, :json, null: false, default: '{}' 

如果你正在使用mysql數據庫,那麼你需要序列化的列。