Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型

本文介绍了使用Golang解析JSON格式数据的方法,特别是如何处理JSON中的数字成员。当使用interface{}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 Golang 解析 JSON  格式数据时,若以 interface{} 接收数字成员,则会按照下列规则进行解析,可见

使用 Golang 对 JSON 结构进行解析(unmarshal)时,JSON 结构中的数字会被解析为 float64 类型:

    bool, for JSON booleans

    float64, for JSON numbers

    string, for JSON strings

    []interface{}, for JSON arrays

    map[string]interface{}, for JSON objects

    nil for JSON null

如果要转换为整型,可用强制类型转换:

 int( a["id"].(float64) )  // 将 interface{} 类型的 “id” 键申明为 float64 类型,再转换为 int 型

遍历 JSON 可以使用 Go 语言内置的 encoding/json 包。 假设有以下 JSON 数据: ```json { "name": "John", "age": 30, "email": "john@example.com", "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" }, "phoneNumbers": [ { "type": "home", "number": "555-1234" }, { "type": "work", "number": "555-5678" } ] } ``` 可以使用以下代码遍历该 JSON: ```go package main import ( "encoding/json" "fmt" ) func main() { jsonData := `{ "name": "John", "age": 30, "email": "john@example.com", "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" }, "phoneNumbers": [ { "type": "home", "number": "555-1234" }, { "type": "work", "number": "555-5678" } ] }` var result map[string]interface{} err := json.Unmarshal([]byte(jsonData), &result) if err != nil { fmt.Println("error:", err) } for key, value := range result { switch valueType := value.(type) { case string: fmt.Println(key, "is string:", valueType) case float64: fmt.Println(key, "is float64:", valueType) case map[string]interface{}: fmt.Println(key, "is an object:") for subKey, subValue := range valueType { fmt.Println(subKey, ":", subValue) } case []interface{}: fmt.Println(key, "is an array:") for i, arrValue := range valueType { fmt.Println(i, ":", arrValue) } default: fmt.Println(key, "is of a different type") } } } ``` 输出结果为: ``` name is string: John age is float64: 30 email is string: john@example.com address is an object: street : 123 Main St city : New York state : NY zip : 10001 phoneNumbers is an array: 0 : map[number:555-1234 type:home] 1 : map[number:555-5678 type:work] ``` 可以看到,遍历 JSON 数据需要使用类型断言,判断当前值的类型,并根据类型进行相应操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值