SUPER-G.EEK.JP

twitter: @hum_op_dev
github: ophum

[Golang] encoding/jsonで文字列の数値を数値型で扱う

目次

以下のようにすることで文字列の数値を数値型で扱うことができます。

 1package main
 2
 3import (
 4	"encoding/json"
 5	"testing"
 6)
 7
 8type Test struct {
 9	Value int `json:"value,string"`
10}
11
12func TestUnmarshal(t *testing.T) {
13	a := []byte(`{"value": "1000"}`)
14
15	var b Test
16	if err := json.Unmarshal(a, &b); err != nil {
17		t.Fatal(err)
18	}
19	if b.Value != 1000 {
20		t.Fatal("want: 1000\ngot:", b.Value)
21	}
22}
23
24func TestMarshal(t *testing.T) {
25	want := `{"value":"1000"}`
26
27	got, err := json.Marshal(&Test{Value: 1000})
28	if err != nil {
29		t.Fatal(err)
30	}
31	if want != string(got) {
32		t.Fatal("want:", want, "\ngot:", string(got))
33	}
34}
Tags: