Slide 1

Slide 1 text

© DMM.com encoding/json v2を予習しよう! DMM.go #10 いっぬ(@yuyu_hf) プラットフォーム開発本部 認可チーム 1

Slide 2

Slide 2 text

© DMM.com 自己紹介 いっぬ(@yuyu_hf) ➢ 合同会社DMM.com(2019/04 - 現在) ○ プラットフォーム開発本部 認可チーム ➢ 認可APIをフルリプレースしています ○ PHP → Go ○ MySQL → TiDB Cloud ○ オンプレ → GKE 2 2

Slide 3

Slide 3 text

© DMM.com encoding/json v2がGOEXPERIMENTに追加されました 2023/10/06 v2のDiscussionが作成される 2025/01/31 v2のProposalが作成される 2025/04/19 GOEXPERIMENTに追加される 今ココ 3

Slide 4

Slide 4 text

© DMM.com 今日の発表のGoal encoding/json v2をわかった気になる! 4

Slide 5

Slide 5 text

© DMM.com 今日話すこと 1. encoding/json v2のデザイン 2. 最新のJSON仕様への追従 3. json struct field tagの追加 4. おわりに 5

Slide 6

Slide 6 text

© DMM.com 1. encoding/json v2のデザイン 6

Slide 7

Slide 7 text

© DMM.com encoding/json v1のデザイン package “json” any []byte any []byte Marshal Unmarshal io.Reader NewDecoder NewEncoder io.Writer encodeState marshal decodeState unmarshal 7

Slide 8

Slide 8 text

© DMM.com encoding/json v2のデザイン https://github.com/golang/go/issues/71497 8

Slide 9

Slide 9 text

© DMM.com encoding/json v2のデザイン https://github.com/golang/go/issues/71497 9

Slide 10

Slide 10 text

© DMM.com json package + jsontext package json package Goの値⇔JSONの値の変換を行う意味的機能を担う。 jsontext package JSONの文法に基づいて処理を行う構文的機能を担う。 10

Slide 11

Slide 11 text

© DMM.com json package + jsontext package json package Goの値⇔JSONの値の変換を行う意味的機能を担う。 jsontext package JSONの文法に基づいて処理を行う構文的機能を担う。 json packageの内部で利用されています 低レベルな APIを利用したいときは jsontext packageを使う 11

Slide 12

Slide 12 text

© DMM.com jsontext package jsontext packageではEncoder/Decoderという仕組みを採用しています。 12

Slide 13

Slide 13 text

© DMM.com func (*Encoder) WriteToken(Token) error func (*Encoder) WriteValue(Value) error func (*Decoder) PeekKind() Kind func (*Decoder) ReadToken() (Token, error) func (*Decoder) ReadValue() (Value, error) func (*Decoder) SkipValue() error func (enc *Encoder) Encode(v any) error func (dec *Decoder) Decode(v any) error v1… 1つのJSONを読み書きする v2 … Token/Valueを読み書きする Encoder/Decoderの違い 13

Slide 14

Slide 14 text

© DMM.com Token TokenとはJSONの字句トークンを表すオブジェクトです。 字句トークンの種類 14 [ ] { } string number boolean null

Slide 15

Slide 15 text

© DMM.com Value ValueとはJSON値を表すオブジェクトです。 JSON値の例 15 {"foo":"bar"}

Slide 16

Slide 16 text

© DMM.com jsontext packageの使い方 JSONの字句トークンを表すオブジェクトを利用してJSONを組み立てること ができます。 key-value間のコロンなどを勝手に補完してくれて嬉しい。 16 b := new(bytes.Buffer) enc := jsontext.NewEncoder(b) _ = enc.WriteToken(jsontext.BeginObject) _ = enc.WriteToken(jsontext.String("hoge")) _ = enc.WriteToken(jsontext.String("fuga")) _ = enc.WriteToken(jsontext.String("foo")) _ = enc.WriteToken(jsontext.String("bar")) _ = enc.WriteToken(jsontext.EndObject) fmt.Println(b.String()) {"hoge":"fuga","foo":"bar"}

Slide 17

Slide 17 text

© DMM.com jsontext packageの使い方 17 _ = enc.WriteToken(jsontext.BeginObject) _ = enc.WriteToken(jsontext.String("hoge")) _ = enc.WriteToken(jsontext.String("fuga")) _ = enc.WriteToken(jsontext.EndObject) _ = enc.WriteValue(jsontext.Value(`{"hoge":"fuga"}`)) Tokenを使ってJSONを組み立てる場合 Valueを使ってJSONを組み立てる場合

Slide 18

Slide 18 text

© DMM.com json package func Marshal(in any, opts ...Options) (out []byte, err error) func MarshalWrite(out io.Writer, in any, opts ...Options) error func MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) error func Unmarshal(in []byte, out any, opts ...Options) error func UnmarshalRead(in io.Reader, out any, opts ...Options) error func UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) error func Marshal(v any) ([]byte, error) func Unmarshal(data []byte, v any) error 18 v1 v2

Slide 19

Slide 19 text

© DMM.com 内部的にjsontext.Encoder/Decoderが利用されている json.Marshal/Unmarshalの中でjsontext.Encoder/Decoderが利用されて います。 func Unmarshal(in []byte, out any, opts ...Options) (err error) { dec := export.GetBufferedDecoder(in, opts...) … func (export) GetBufferedDecoder(b []byte, o ...Options) *Decoder { return getBufferedDecoder(b, o...) } json package jsontext package 19

Slide 20

Slide 20 text

© DMM.com json packageの変更点(私的観点で抜粋) 1. Marshal/Unmarshalのstream apiへの対応 2. Marshal/Unmarshalの振る舞いを変更できる 3. MarshalerTo/UnmarshalerFromインターフェースの追加 4. jsontext package機能を分離した 20

Slide 21

Slide 21 text

© DMM.com もうio.ReadAllしなくていい。 1. Marshal/Unmarshalのstream apiへの対応 func XXX(r io.Reader) YYY { b, err := io.ReadAll(r) if err != nil { ... } var m map[string]interface{} if err := json.Unmarshal(b, m); err != nil { ... } ... } func XXX(r io.Reader) YYY { var m map[string]interface{} if err := json.UnmarshalRead(r, m); err != nil { ... } ... } v1 v2 21

Slide 22

Slide 22 text

© DMM.com 2. Marshal/Unmarshalの振る舞いを変更できる encoding/json v2ではMarshal/Unmarshal時にOptionsを引数として受け 取ることができます。 func XXX(r io.Reader) YYY { var m map[string]interface{} if err := json.UnmarshalRead(r, m, json.RejectUnknownMembers(true)); err != nil { ... } ... } 22

Slide 23

Slide 23 text

© DMM.com v1でもEncoder/Decoderは振る舞いを変更できる v1でもEncoder/Decoderのメソッドで振る舞いを変更できます。 func XXX(r io.Reader) YYY { d := json.NewDecoder(r) d.DisallowUnknownFields() var m map[string]interface{} if err := d.Decode(m); err != nil { ... } ... } 23

Slide 24

Slide 24 text

© DMM.com 3. MarshalerTo/UnmarshalerFromインターフェースの追加 type Marshaler interface { MarshalJSON() ([]byte, error) } type MarshalerTo interface { MarshalJSONTo(*jsontext.Encoder) error } type Unmarshaler interface { UnmarshalJSON([]byte) error } type UnmarshalerFrom interface { UnmarshalJSONFrom(*jsontext.Decoder) error } type Marshaler interface { MarshalJSON() ([]byte, error) } type Unmarshaler interface { UnmarshalJSON([]byte) error } v1 v2 24

Slide 25

Slide 25 text

© DMM.com MarshalJSONとMarshalJSONToの違い MarshalJSONの場合 MarshalJSON毎に[]byteがメモリアロケートされる(場合も)。 MarshalJSONToの場合 引数で渡したjsontext.Encoderのバッファーに値を追加する。 25

Slide 26

Slide 26 text

© DMM.com v2のMarshalのパフォーマンス https://github.com/golang/go/issues/71497#issuecomment-2626484348 26

Slide 27

Slide 27 text

© DMM.com v2のUnmarshalパフォーマンス https://github.com/golang/go/issues/71497#issuecomment-2626484348 27

Slide 28

Slide 28 text

© DMM.com 4. jsontext package機能を分割した理由 https://github.com/golang/go/discussions/63397 28

Slide 29

Slide 29 text

© DMM.com 4. jsontext package機能を分割した理由 jsontext packageでreflect packageへの依存を無くすことでバイナリサイズ を削減しています。 バイナリサイズの大きさが問題となるアプリケーションでjsontext packageを 利用してもらいやすくなる。 • TinyGo • GopherJS • WASI • etc… 29

Slide 30

Slide 30 text

© DMM.com any型の利用によりバイナリサイズが大きくなる encoding/json v1ではany型を利用しているので、採用していないときと比 較してバイナリサイズが大きくなる。 func (d *decodeState) unmarshal(v any) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Pointer || rv.IsNil() { return &InvalidUnmarshalError{reflect.TypeOf(v)} } ... func (dec *Decoder) Decode(v any) error { ... err = dec.d.unmarshal(v) 30

Slide 31

Slide 31 text

© DMM.com v2ではjsontext packageからany型に対する処理を分離 json packageにany型に対する処理を寄せて、jsontext packageではany 型を使用しないように設計されています。 (このスライドだけだとわかりづらい😭) func Marshal(in any, opts ...Options) (out []byte, err error) { ... err = marshalEncode(enc, in, &xe.Struct) func marshalEncode(out *jsontext.Encoder, in any, mo *jsonopts.Struct) (err error) { v := reflect.ValueOf(in) if !v.IsValid() || (v.Kind() == reflect.Pointer && v.IsNil()) { return out.WriteToken(jsontext.Null) } ... 31

Slide 32

Slide 32 text

© DMM.com 2. 最新のJSON仕様への追従 32

Slide 33

Slide 33 text

© DMM.com encoding/json v1はRFC 7159に準拠している https://pkg.go.dev/encoding/json 33

Slide 34

Slide 34 text

© DMM.com 最新のJSON仕様に追従していない RFC 8259違反の例 // 無効な UTF-8 シーケンス(0xff を含む) invalidJSON := []byte(`{"text":"hello` + string([]byte{0xff}) + `"}`) var result map[string]string err := json.Unmarshal(invalidJSON, &result); if err != nil { fmt.Println("Unmarshal error:", err) } else { fmt.Println("Result:", result) } 実行結果は 成功 34

Slide 35

Slide 35 text

© DMM.com encoding/json v2でのJSON仕様の追従 • RFC 6901 (JSON Pointer) • RFC 7493 (The I-JSON Message Format) • RFC 8259 (The JavaScript Object Notation (JSON) Data Interchange Format) • RFC 8785 (JSON Canonicalization Scheme (JCS)) 35

Slide 36

Slide 36 text

© DMM.com encoding/json v2でのJSON仕様の追従 • RFC 6901 (JSON Pointer) • RFC 7493 (The I-JSON Message Format) • RFC 8259 (The JavaScript Object Notation (JSON) Data Interchange Format) • RFC 8785 (JSON Canonicalization Scheme (JCS)) 36 最新のJSONの国際標準に追従しています。

Slide 37

Slide 37 text

© DMM.com encoding/json v2の実行結果 RFC 8259違反の例 // 無効な UTF-8 シーケンス(0xff を含む) invalidJSON := []byte(`{"text":"hello` + string([]byte{0xff}) + `"}`) var result map[string]string err := json.Unmarshal(invalidJSON, &result); if err != nil { fmt.Println("Unmarshal error:", err) } else { fmt.Println("Result:", result) } 実行結果は エラー 37

Slide 38

Slide 38 text

© DMM.com v1からv2への移行ステップ jsonv1.Marshal(v) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1()) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false)) ↓ jsonv2.Marshal(in, jsonv1.StringifyWithLegacySemantics(true), …) ↓ jsonv2.Marshal(v, ..., jsonv2.DefaultOptionsV2()) ↓ jsonv2.Marshal(v) 38

Slide 39

Slide 39 text

© DMM.com v1からv2への移行ステップ jsonv1.Marshal(v) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1()) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false)) ↓ jsonv2.Marshal(in, jsonv1.StringifyWithLegacySemantics(true), …) ↓ jsonv2.Marshal(v, ..., jsonv2.DefaultOptionsV2()) ↓ jsonv2.Marshal(v) v1と同じOptionsを利用できる 39

Slide 40

Slide 40 text

© DMM.com v1からv2への移行ステップ jsonv1.Marshal(v) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1()) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false)) ↓ jsonv2.Marshal(in, jsonv1.StringifyWithLegacySemantics(true), …) ↓ jsonv2.Marshal(v, ..., jsonv2.DefaultOptionsV2()) ↓ jsonv2.Marshal(v) v1から徐々に v2のデフォルトの Optionsに寄せる 40

Slide 41

Slide 41 text

© DMM.com v1からv2への移行ステップ jsonv1.Marshal(v) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1()) ↓ jsonv2.Marshal(in, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false)) ↓ jsonv2.Marshal(in, jsonv1.StringifyWithLegacySemantics(true), …) ↓ jsonv2.Marshal(v, ..., jsonv2.DefaultOptionsV2()) ↓ jsonv2.Marshal(v) v2のデフォルトの Optionsに移行しきったら完了 41

Slide 42

Slide 42 text

© DMM.com 3. json struct field tagの追加 42

Slide 43

Slide 43 text

© DMM.com v2から新しいstruct field tagが追加されました 追加されたstruct field tagをいくつか抜粋しました。 • inline • unknown • format 43

Slide 44

Slide 44 text

© DMM.com inline 型を埋め込まなくてもInline可能になりました。 44 type Base struct { Embeded string } type Container struct { Base Hoge int Inlined struct { Foo string Bar string } `json:",inline"` } { "Embeded": "", "Hoge": 0, "Foo": "", "Bar": "" }

Slide 45

Slide 45 text

© DMM.com unknown 45 const input = `{ "Hoge": "Fuga", "Foo": "Bar" }` type A struct { Hoge string Unknown jsontext.Value `json:",unknown"` } var a A _ = json.Unmarshal([]byte(input), &a) b, _ := json.Marshal(a) fmt.Println(string(b)) {"Hoge":"Fuga","Foo":"Bar"} 実行結果 keyに対応するフィールドが無くても unknownフィールドに格納してくれる

Slide 46

Slide 46 text

© DMM.com unknown無しのとき 46 const input = `{ "Hoge": "Fuga", "Foo": "Bar" }` type A struct { Hoge string } var a A _ = json.Unmarshal([]byte(input), &a) b, _ := json.Marshal(a) fmt.Println(string(b)) {"Hoge":"Fuga"} 実行結果 FooBarが欠落

Slide 47

Slide 47 text

© DMM.com format json.Marshal時の値のフォーマットを指定することができます。 47

Slide 48

Slide 48 text

© DMM.com format バックエンドAPIのUI層でHTTP Response Bodyを組み立てるときに time.TimeをDateに変換する処理を書かなくてよくなる。 48 { "TimeDateOnly": "2000-01-01", "TimeUnixSec": 946684800 } v := struct { TimeDateOnly time.Time `json:",format:'2006-01-02'"` TimeUnixSec time.Time `json:",format:unix"` }{ TimeDateOnly: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), TimeUnixSec: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), } b, _ := json.Marshal(&v)

Slide 49

Slide 49 text

© DMM.com おわりに 49

Slide 50

Slide 50 text

© DMM.com おわりに 本発表ではencoding/json v2について簡単に紹介させていただきました。 発表で紹介できなかった内容もたくさんあるので、ぜひProposalを読んだり 実装を調べてみてください! 50

Slide 51

Slide 51 text

© DMM.com 参考 • Discussion(https://github.com/golang/go/discussions/63397) • Proposal(https://github.com/golang/go/issues/71497) • Proposalの実装(https://github.com/go-json-experiment/json) • Proposalの実装のパフォーマンステスト (https://github.com/go-json-experiment/jsonbench) • GopherCon 2023: The Future of JSON in Go - Joe Tsai (https://www.youtube.com/watch?v=avilmOcHKHE) 51