Skip to content

Instantly share code, notes, and snippets.

@hakamata-rui
Created October 27, 2017 06:07
Show Gist options
  • Save hakamata-rui/59ec49ca80a3873d45e3b86293340c48 to your computer and use it in GitHub Desktop.
Save hakamata-rui/59ec49ca80a3873d45e3b86293340c48 to your computer and use it in GitHub Desktop.
途中の一部のstructだけ構造体にマッピングしたい場合
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type Field struct {
FieldA int `json:"field_a"`
FieldB int `json:"field_b"`
Fields *OtherField `json:"fields"` // Pointer型にしないと invalid recursive type Field のエラーになる
}
type OtherField struct {
FieldX string `json:"field_x"`
FieldY string `json:"field_y"`
}
func main() {
j := `
{
"field_a": 100,
"field_b": 200,
"fields": {
"field_x": "hoge",
"field_y": "fuga"
}
}`
var f map[string]interface{}
json.Unmarshal([]byte(j), &f)
fmt.Printf("%f %f\n", f["field_a"], f["field_b"]) // 100.000000 200.000000
f2, _ := f["fields"].(map[string]interface{})
fmt.Printf("%s %s\n", f2["field_x"], f2["field_y"]) // hoge fuga
// もし途中の一部のstructだけ構造体にマッピングしたい場合
fmt.Println(reflect.TypeOf(f2)) // map[string]interface {}
tmp, _ := json.Marshal(f2)
field := OtherField{}
json.Unmarshal(tmp, &field)
fmt.Printf("%s %s\n", field.FieldX, field.FieldY) // hoge fuga
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment