2015-05-29 24 views
0

我有JSON響應。Ruby:TypeError:無法將字符串轉換爲整數

result = { 
    "owner":{ 
    "uid":"bb4123ac7950435eb516e2a47940b675", 
    "firstName":"Tester", 
    "lastName":"Test5577" 
    } 
} 

我想提取「uid」,但得到以下錯誤。

紅寶石:類型錯誤:不能轉換成字符串整數

我的代碼是:

@jdoc =JSON.parse(result) 

@uid = @jdoc.fetch("owner").first.fetch("uid").to_i() #Getting error here. 

將是您的支持非常感激。

+0

我已經在控制檯嘗試這樣做,得到了以下結果 '[29]撬(主)> @uid = @ jdoc.fetch( 「所有者」)。first.fetch( 「UID」)。to_i () TypeError:無法將字符串轉換爲整數 from(pry):28:in fetch'' '[30] pry(main)> @uid = @ jdoc.fetch(「owner」)。fetch 「uid」)。to_i() => 0 [31] pry(main)> @uid = @ jdoc.fetch(「owner」)。fetch(「uid」) =>「bb4123ac7950435eb516e2a47940b675」' –

+0

Thanks Amit這是工作很棒@ jdoc.fetch(「所有者」)。fetch(「uid」)。謝謝:-) – Zaf

回答

1

你的代碼中的一個小小的變化應該得到正確的數據:

@jdoc = JSON.parse(result) 
@uid = @json['owner']['uid'] #=> "bb4123ac7950435eb516e2a47940b675" 

此外,您試圖在代碼中將字符串「bb4123ac7950435eb516e2a47940b675」轉換爲整數:to_i()。這將是0,因爲uid是一串字母數字字符,而不是某些隨機數字/整數的組合。我建議您將該信息保存在varchar列中。

+1

謝謝蘇里亞。你是明星。它正在使用@ uid = @jdoc [「owner」] [「uid」]。非常感謝您的幫助。 – Zaf

0

您可以通過以下方式訪問UID:

@jdoc = JSON.parse(result) 
@uid = @json['owner']['uid'] 
@uid = Integer(@uid) rescue 0 
+0

謝謝。它正在使用@ uid = @jdoc [「owner」] [「uid」]。非常感謝您的幫助。 – Zaf

0

可否請您打印後JSON.parse(result)

者均基於UID包含字符串裏面有什麼@jdoc所以你會用整數接受0作爲輸出中

"bb4123ac7950435eb516e2a47940b675".to_i => # 0 
"111".to_i => # 111 
+0

謝謝@Thounder。 – Zaf

0

你可以試試這個。我希望這能幫到您。

@uid = @jdoc.fetch("owner").first.fetch("uid").to_i() 

## OUTPUT 

# If you do it like this you will get follwing error 
TypeError: can't convert String into Integer 

但是,如果你會做下面你會得到慾望的結果。

@uid = @jdoc.fetch("owner").fetch("uid") 

##OUTPUT 

"bb4123ac7950435eb516e2a47940b675"