日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Json and Go

發布時間:2025/3/18 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Json and Go 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Reference https://blog.go-zh.org/json-a...

Encoding

Encode的基本用法是

package mainimport ("encoding/json""fmt""os" )type Message struct {Name stringBody stringTime int64 }func main() {message := Message{"Tom", "Hello", 1294706395881547000}b, err := json.Marshal(message)if err != nil {fmt.Fprintf(os.Stderr, "Failed to Marshal!")os.Exit(1)}fmt.Printf("%s", b) }

輸出為:

{"Name":"Tom","Body":"Hello","Time":1294706395881547000} func Marshal(v interface{}) ([]byte, error)

Only data structures that can be represented as valid JSON will be encoded:

  • JSON objects only support string as keys.
  • Channel, complex, and function types cannot be encoded.
  • Cyclic data structures are not supported.
  • Pointers will be encoded as the values they point to(or null if the pointer is nil)

json package 只能access the exportede fields. 也就是首字母大寫的field. 也就是在data structure中的首字母大寫的field才會present in JSON output

Decoding

// We must first create a place where the decoded data will be stored var output Message // Please note that passing the pointer to output decodeErr := json.Unmarshal(b, &output) if decodeErr != nil {fmt.Fprintf(os.Stderr, "Failed to Unmarshal json data!err:%s", err)os.Exit(1) }fmt.Printf("%+v\n", output)

Unmarshal是怎么確認json field與data structure的對應關系呢?,其實是通過以下來判斷的(優先級從高到低).比如對于JSON Field "Foo"來說,

  • An exported field with a tag of "Foo".
  • An exported field named "Foo"
  • An exported field named "FOO" or "FoO" or some other case-insensitive match of "Foo"

總結下來是: Tag -> Foo -> FOO(case-insensitive match)
tag的判定規則如下

// Field appears in JSON as key "myName". Field int `json:"myName"`// Field appears in JSON as key "myName" and // the field is omitted from the object if its value is empty, // as defined above. Field int `json:"myName,omitempty"`// Field appears in JSON as key "Field" (the default), but // the field is skipped if empty. // Note the leading comma. Field int `json:",omitempty"`// Field is ignored by this package. Field int `json:"-"`// Field appears in JSON as key "-". Field int `json:"-,"`

如果json data 與data structure中只有部分field匹配怎么辦?

var unmatchedOutput UnmatchMessage message1 := //` `代表原生字符串面值,沒有轉義操作,全是字符串的字面值 []byte{`{"Name":"Tom","Body":"Hello","Time":1294706395881547000}`} decodeErr1 := json.Unmarshal(b, &unmatchedOutput) if decodeErr1 != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal json data! err:", err)os.Exit(1) } fmt.Printf("%+v\n", unmatchedOutput)

輸出為

{Name:Tom Boy: Tim:0}

從上看出,Unmarshal只會decode符合上述3條件的field
This behavior is particularly useful when you wish to pick only a few specific fields out of a large JSON blob.

Generic JSON with interface{}

Decoding arbitrary data

以上2章先跳過去

Reference Types

Unmarshal會為Reference Types自動allocated a memory. 注意這里僅僅為在json 中存在的data allocate memory.

package mainimport ("encoding/json""fmt""os" )type FamilyMember struct {Name stringAge intParents []string }func main() {family := FamilyMember{"Andy", 26, []string{"Tom", "Lucy"}}b, err := json.Marshal(family)if err != nil {fmt.Fprintf(os.Stderr, "Failed to Marshal family!err:%s", err)os.Exit(1)}fmt.Printf("%s\n", b)// 注意,此時Parents slice是nil. 在Unmarshal時,會自動為其allcated memory.var output FamilyMemberdecodeErr := json.Unmarshal(b, &output)if decodeErr != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal!err:%s", err.Error())os.Exit(1)}fmt.Printf("%+v\n", output) }

對于指針也是一樣的

package mainimport ("encoding/json""fmt""os" )type Bar int type Foo struct {Bar *Bar }func main() {b := []byte(`{"Bar":1234}`)var data Fooerr := json.Unmarshal(b, &data)if err != nil {fmt.Fprintf(os.Stderr, "Failed to unmarshal!err:%s", err.Error())os.Exit(1)}fmt.Printf("%+v\n", data)fmt.Printf("%+v\n", *(data.Bar)) }

輸出為:

{Bar:0xc42001a120} // 注意此時的地址不為nil了,因為在Unmarshal已經為其allocated了memory 1234

但是需要注意,Unmarshal只會為json data匹配的field 分配內存,對于沒有匹配的,可能還是nil. 所以對于如下的structure,在使用之前還需要認為的判斷是否為nil.

type IncomingMessage struct {Cmd *CommandMsg *Message }

Streaming Encoders and Decoders

package mainimport ("encoding/json""log""os" )func main() {dec := json.NewDecoder(os.Stdin)enc := json.NewEncoder(os.Stdout)for {var v map[string]interface{}if err := dec.Decode(&v); err != nil {log.Println(err)return}for k := range v {if k != "Name" {delete(v, k)}}if err := enc.Encode(&v); err != nil {log.Println(err)}} }

總結

以上是生活随笔為你收集整理的Json and Go的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。