Skip to content

Instantly share code, notes, and snippets.

@hakamata-rui
Created October 26, 2017 15:46
Show Gist options
  • Save hakamata-rui/c715251180a40580d1eb002f73c683de to your computer and use it in GitHub Desktop.
Save hakamata-rui/c715251180a40580d1eb002f73c683de to your computer and use it in GitHub Desktop.
Golangで再帰型のJSONをパースする方法
package main
import (
"encoding/json"
"fmt"
)
type Field struct {
FieldA int `json:"field_a"`
FieldB int `json:"field_b"`
Fields *Field `json:"fields"` // Pointer型にしないと invalid recursive type Field のエラーになる
}
func main() {
j1 := `
{
"field_a": 100,
"field_b": 200
}`
var f1 Field
json.Unmarshal([]byte(j1), &f1)
fmt.Printf("%v\n", f1) // {100 200 <nil>}
j2 := `
{
"field_a": 100,
"field_b": 200,
"fields": {
"field_a": 300,
"field_b": 400
}
}`
var f2 Field
json.Unmarshal([]byte(j2), &f2)
fmt.Printf("%v\n", f2) // {100 200 0x4211aa2e0}
fmt.Printf("%v\n", *f2.Fields) // {300 400 <nil>}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment