18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

空のスライスを json.Marshal すると、"[]" じゃなく "null" になる

Last updated at Posted at 2017-12-10

golang で JSON 返す API つくった時にハマったのでメモ。

現象

スライス変数の作成方法によって内容が変わる

null になる

type (
	Test struct {
		Tests []string `json:"tests"`
	}
)

func main() {
	var t Test
	var tests []string
	t.Tests = tests
	res, _ := json.Marshal(t)
	println(string(res))
}
// {"tests":null}

[] になる

type (
	Test struct {
		Tests []string `json:"tests"`
	}
)

func main() {
	var t Test
	tests := make([]string, 0) // []string{} でも同じ
	t.Tests = tests
	res, _ := json.Marshal(t)
	println(string(res))
}
// {"tests":[]}

null で返すと Swift などで使う場合 optional で受け取らないといけないので注意しましょう(自戒)

18
9
1

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
18
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?