golang JSON操作

第一种:使用encoding/json

解码:
 

type myjson struct{

    Code int `json:"code"`

    Xxx struct { ... } `json: "xxx"`

}

在结构中声明,必须要首字母大写,可以struct嵌套结构。
 

var data myjson

json.Unmarshal([]byte(jsonStr), &data)

还可以有更灵活的办法,这样就不用定义struct了。
 

var data map[string]interface{}

json.Unmarshal([]byte(jsonStr), &data)

编码:
 

data,error = json.Marshal(value)

data,error = json.MarshalIndent(value,""," ")

value为任何类型的数据结构,返回的data可以使用string(data)转为String型,MarshalIndent的区别在于他能够格式化输出,参数2是前缀,参数3是缩进。

第二种:使用go-simplejson(go get -u github.com/bitly/go-simplejson

// 读取json
js, err := simplejson.NewJson([]byte(jsonStr))
// 获取数组,可以用 range 遍历
arr,err := js.Get("数组").Array()
// 获取数组元素,根据索引
value := js.Get("数组").GetIndex(x)
// 获取属性,String型,还有MustInt() ,具体可以看文档 https://godoc.org/github.com/bitly/go-simplejson
v := value.Get("属性").MustString()

 

猜你喜欢

转载自blog.csdn.net/hjmnasdkl/article/details/81252193