Upgrade to Pro — share decks privately, control downloads, hide ads and more …

encoding/json v2を予習しよう!

encoding/json v2を予習しよう!

DMM.go #10の登壇資料です。
https://dmm.connpass.com/event/346087/

Avatar for yuyu_hf

yuyu_hf

May 15, 2025
Tweet

More Decks by yuyu_hf

Other Decks in Technology

Transcript

  1. © DMM.com 自己紹介 いっぬ(@yuyu_hf) ➢ 合同会社DMM.com(2019/04 - 現在) ◦ プラットフォーム開発本部

    認可チーム ➢ 認可APIをフルリプレースしています ◦ PHP → Go ◦ MySQL → TiDB Cloud ◦ オンプレ → GKE 2 2
  2. © DMM.com encoding/json v1のデザイン package “json” any []byte any []byte

    Marshal Unmarshal io.Reader NewDecoder NewEncoder io.Writer encodeState marshal decodeState unmarshal 7
  3. © DMM.com json package + jsontext package json package Goの値⇔JSONの値の変換を行う意味的機能を担う。

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

    jsontext package JSONの文法に基づいて処理を行う構文的機能を担う。 json packageの内部で利用されています 低レベルな APIを利用したいときは jsontext packageを使う 11
  5. © 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
  6. © 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"}
  7. © 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を組み立てる場合
  8. © 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
  9. © 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
  10. © 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
  11. © 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
  12. © 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
  13. © 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
  14. © 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
  15. © 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
  16. © 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
  17. © 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
  18. © 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の国際標準に追従しています。
  19. © 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
  20. © 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
  21. © 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
  22. © 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
  23. © 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
  24. © 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": "" }
  25. © 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フィールドに格納してくれる
  26. © 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が欠落
  27. © 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)
  28. © 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