LoginSignup
0
1

More than 5 years have passed since last update.

Go の json.Unmarshal の罠

Posted at

実際に仕事でミスった話。

まあまずはソースコード。

go
package main

import (
    "encoding/json"
    "fmt"
)

type hoge struct {
    m map[string]interface{}
}

func (h *hoge) load(text string) error {
    var bytes = []byte(text)
    return json.Unmarshal(bytes, &h.m)

}

func main() {
    h := hoge{}

    h.load(`{"foo":"bar"}`)
    fmt.Println(h) //=> {map[foo:bar]}

    h.load(`{"baz":"qux"}`)
    fmt.Println(h) //=> {map[foo:bar baz:qux]}
}

上記のとおり。

要するに。
空っぽじゃない map を json.Unmarshal に渡すと、もともと入っていた値は消されずに残る。
ドキュメントにもそう書いてある。

まあ、オブジェクトを使いまわしたのが敗因だね。
毎回ちゃんと綺麗な体で仕事に当たろうというのが今回の教訓かな。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1