unmarshaling json to inner struct in golang

Back to Bar

sometimes we only want one small part of a bigger go struct while unmarshaling a big json object. with this small code you only get the inner struct that is important, see this very simple example:

{
	"Name": "asdfasdf", 
	"Data": {
		"A": 12
		"B": 4
	}
}

suppose you only want the information in the Data object, first let's define our types:

type Body struct {
	Name string
	Data *Inner
}

type Inner struct {
	A int
	B int
}

hence only the Inner field in Body is desired. to unmarshal this use the code bellow:

package main

import (
	"encoding/json"
	"fmt"
)

const s = `{"Name": "asdfasdf", "Data":{"A": 12, "B": 4}}`

type Body struct {
	Name string
	Data interface{}
}

type Inner struct {
	A int
	B int
}

func main() {
	data := Inner{}
	json.Unmarshal([]byte(s), &Body{Data: &data})
	fmt.Printf("%#v\n", data)
}

notice that only data in on scope, the Body struct only existed during the unmarshal.

this is useful for saving a small piece of memory.