Golang 语言操作 JSON

Golang 语言操作 JSON

使用 encoding/json

package main

import (
    "encoding/json"
    "fmt"
)

// User ...
type User struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

func main() {

    buf, _ := json.Marshal(User{
        Email:    "xxxx@example.com",
        Password: "123456",
    })

    fmt.Printf("%#v\n", buf)
    // 解析
    user := User{}
    json.Unmarshal([]byte(`{
"email": "xxx@example.com",
"password": "123456"
}`), &user)
    fmt.Printf("%#v\n", user)
}

如果你需要对自定义结构体 Marshal 和Unmarshal 来到达特殊解析的逻辑

  • 自定义 Marshal 只需要自定义 MarshalJSON
  • 自定义 Unmarshal 只需要自定义 UnmarshalJSON
   package main

    import (
        "encoding/json"
        "fmt"
    )

    // User ...
    type User struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    }

    func main() {

        buf, _ := json.Marshal(User{
            Email:    "xxxx@example.com",
            Password: "123456",
        })

        fmt.Printf("%#v\n", buf)
        // 解析
        user := User{}
        json.Unmarshal([]byte(`{
            "email": "xxx@example.com",
            "password": "123456"
            }`), &user)
        fmt.Printf("%#v\n", user)
    }

    // MarshalJSON ...
    func (u User) MarshalJSON() (b []byte, err error) {
        fmt.Printf("%s\n", u.Email)
        fmt.Print("MarshalJSON\n")
        return
    }

    // UnmarshalJSON ...
    func (u User) UnmarshalJSON(b []byte) (err error) {
        fmt.Printf("u.Email%s\n", u.Email)
        fmt.Printf("b is %s\n", b)
        fmt.Print("UnmarshalJSON\n")
        return
    }

最后

  • 其实这一篇就够了:https://colobu.com/2017/06/21/json-tricks-in-Go/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
遍历 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
发出的红包

打赏作者

CoLiuRs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值