JSON, nested json objects NOT arrays

So basically i am playing with JSON and nested JSON objects (not in the form of arrays []) using structs. I bet this is really simple but why am i struggling to create a nested JSON object 1 level deep using two struct types?

package main

import (
	"encoding/json"
	"fmt"
)

type MetaData struct {
	Country string `json:"countryScope"`
	Asset   string `json:"assetScope"`
}

type BusEvent struct {
	MedaData MetaData `json:"metaData"`
	Name string
}

func main() {
	resp := BusEvent{
		MetaData{
			Country: "test",
			Asset:   "test",
		},
		Name: "test",
	}
	js, _ := json.Marshal(resp)
	fmt.Printf("%s", js)
}

https://play.golang.org/p/siMDC2MNX-V

The failure is as follows:

./prog.go:20:11: mixture of field:value and value initializers

This (MedaData) is probably a typo.

The error message says it all. Do this:

	resp := BusEvent{
		MetaData: MetaData{
			Country: "test",
			Asset:   "test",
		},
		Name: "test",
	}

But this is not related to JSON, just how structs are build.

See Go Playground - The Go Programming Language for the output:

{"metaData":{"countryScope":"test","assetScope":"test"},"Name":"test"}

Thank you @lutzhorn! I knew someone would just put me on the straight an narrow. Brilliant thank you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.