2014-09-28 32 views
1

我想使用Google bigquery gem(https://rubygems.org/gems/bigquery)創建一個表名列表。到目前爲止,這是我自己寫的:在Ruby中獲取BigQuery表列表

require 'json' 

bqRepsonse = bq.tables('myDataSet') 

bqRepsonseCleaned = bqRepsonse.to_s.gsub("=>", ":") 

data = JSON.parse(bqRepsonseCleaned) 

tableListing = [] 

data["tableID"]["type"].each do |item| 
    case item["type"] 
    when 'TABLE' 
    bqTableList << item["tableId"] 
    else 
    end 
end 

如果我打印bqResponse,我得到這樣的結果:

[{ 「種」=> 「的BigQuery#表」, 「身份證」 =>「curious-idea-532:dataset_test_4.TableA」, 「tableReference」=> {「projectId」=>「curious-idea-532」, 「datasetId」=>「dataset_test_4」,「tableId」=> TableA「},」type「=>」TABLE「}, {」kind「=>」bigquery#table「, 」id「=>」curious-idea-532:dataset_test_4.TableB「, 」tableReference「= > {「projectId」=>「curious-idea-532」, 「datasetId」=>「dataset_test_4」,「tableId」=>「TableB」},「type」=>「TABLE」}, {「kind」=>「bigquery#table」, 「id」=> curious-idea-532:dataset_test_4.TableC「, 」tableReference「=> {」projectId「=>」curious-idea-532「, 」datasetId「=>」dataset_test_4「,」tableId「=>」TableC「} ,「type」=>「TABLE」}, {「kind」=>「bigquery#table」, 「id」=>「curious-idea-532:dataset_test_4.TableD」, 「tableReference」=> {「專案編號 「=>」 好奇-想法-532" , 「資料集」=> 「dataset_test_4」, 「TABLEID」=> 「表D」}, 「類型」=> 「TABLE」}]

並運行代碼會拋出錯誤

`[]':字符串的沒有隱式轉換成整數(類型錯誤)

不知道在哪裏糾正。我期望的結果是:

tableListing = 「表A」, 「表B」, 「表C」, 「表D」]

預先感謝您的諮詢。

回答

1

試試這個:

require 'json' 

string = '[{"kind": "bigquery#table", "id": "curious-idea-532:dataset_test_4.TableA", "tableReference" : {"projectId":"curious-idea-532", "datasetId":"dataset_test_4", "tableId":"TableA"}, "type":"TABLE"}, {"kind":"bigquery#table", "id":"curious-idea-532:dataset_test_4.TableB", "tableReference":{"projectId":"curious-idea-532", "datasetId":"dataset_test_4", "tableId":"TableB"}, "type":"TABLE"}, {"kind":"bigquery#table", "id":"curious-idea-532:dataset_test_4.TableC", "tableReference":{"projectId":"curious-idea-532", "datasetId":"dataset_test_4", "tableId":"TableC"}, "type":"TABLE"}, {"kind":"bigquery#table", "id":"curious-idea-532:dataset_test_4.TableD", "tableReference":{"projectId":"curious-idea-532", "datasetId":"dataset_test_4", "tableId":"TableD"}, "type":"TABLE"}]' 

data = JSON.parse(string) 

tableListing = [] 

# Here we are iterating over the data instead of its child element 
data.each do |item| 
    case item["type"] 
    when 'TABLE' 
    tableListing << item["tableReference"]["tableId"] 
    else 
    end 
end 

puts tableListing 
+1

,完美的工作,謝謝! – 2014-09-28 14:34:55