」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何用float64值存儲在GO中的字符串中解碼JSON字符串?

如何用float64值存儲在GO中的字符串中解碼JSON字符串?

發佈於2025-03-23
瀏覽:218

How to Decode JSON Strings with Float64 Values Stored as Strings in Go?
在go

Understanding the Error:

When attempting to decode a JSON string like "{"name":"Galaxy Nexus", "price":"3460.00"}" using the json.Unmarshal function, you might encounter the following錯誤:

的go go gooth of go faloats

此錯誤發生是因為JSON解碼器試圖直接將Float64數字的字符串表示形式直接轉換為FLOAT64值直接轉換為FLOAT64值,這是不支持的。 notation 要解決此問題,您需要使用類型轉換註釋來明確指示解碼器將字符串視為float64。該註釋被添加到產品結構中的字段定義中:類型product struct { 名稱字符串 Price Float64`json:“,string”` }

“,字符串”標籤告訴JSON解碼器,價格字段應將其轉換為float64。

byte(s),&pro) 如果err == nil { fmt.printf(“%v \ n”,pro) } 別的 { fmt.println(err) fmt.printf(“%v \ n”,pro) } }

json: cannot unmarshal string into Go value of type float64
Expected Output:

Running this code will produce the expected output:{Name:Galaxy Nexus Price:3460}

The json.Unmarshal function successfully decoded the JSON string and converted the price from a string to a float64。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3