likes
comments
collection
share

go encoding/json 介绍

作者站长头像
站长
· 阅读数 22

由于我一直是一名前端工程师,所以我会在前端的角度将js中的json操作和go中的操作做一个类比方便大家的理解。

将字符串转换为对象

js : JSON.parse(`{"name":"cfl"}`)go : json.Unmarshal

jsonStr := `{
         "name":"cfl",
        "age":10,
        "friend":[{"name":"sx",
            "age":10
        }]
    }`
    type User struct {
        Name   string
        Age    int64
        Friend []User
    }
    var cfl User
    json.Unmarshal([]byte(jsonStr), &cfl)
    fmt.Printf("%+v", cfl)

将对象转换为json

js: JSON.stringifygo: json.Marshal

type User struct {
        Name   string
        Age    int64
        Friend []User
    }
    cfl := User{
        Name: "cfl",
        Age:  10,
        Friend: []User{
            {Name: "sx", Age: 10},
        },
    }

    jsonStr, _ := json.Marshal(cfl)
    fmt.Printf("%v\n", string(jsonStr))

其他的常用方法

json.Valid(byte[]) //校验json字符串是否合法
json.Indent  //按照一定的格式缩进 
json.Compact  //压缩
json.MarshalIndent //转换回带缩进的json字符串

参考资料 encoding/jso

转载自:https://segmentfault.com/a/1190000021035719
评论
请登录