go: Marshal and Unmarshal json

Here is an example playing with json, see https://play.golang.org/p/fHA1im6vPIG

package main

import "encoding/json"
import "fmt"
import "strings"

type personType struct {
	First   string `json:"first"`
	Last    string `json:"last"`
	Address string `json:"address"`
type AddressType struct {
	Number int    `json:"number"`
	Street string `json:"street"`
	City   string `json:"city"`
type complexPersonType struct {
	First   string      `json:"first"`
	Last    string      `json:"last"`
	Address AddressType `json:"address"`

func main() {
	person := &personType{
		First:   "Bob",
		Last:    "Adams",
		Address: "BeReplacedAddress",
	personBytes, _ := json.Marshal(person)
	fmt.Printf("%#v\nstring          %#v\n\n", person, string(personBytes))

	address := &AddressType{
		Number: 10,
		Street: "Downing Street",
		City:   "Westminster",
	addressBytes, _ := json.Marshal(address)
	fmt.Printf("%#v\nstring          %#v\n\n", address, string(addressBytes))

	fullPersonString := strings.Replace(string(personBytes), "\"BeReplacedAddress\"", string(addressBytes), -1)
	fmt.Printf("after replacing %#v\n", fullPersonString)

	var fullComplexPerson complexPersonType
	_ = json.Unmarshal([]byte(fullPersonString), &fullComplexPerson)
	fmt.Printf("%#v\n\n", fullComplexPerson)

	complexPerson := &complexPersonType{
		First:   "Chuck",
		Last:    "Adams",
		Address: AddressType{Number: 203, City: "London"},
	complexPersonBytes, _ := json.Marshal(complexPerson)
	fmt.Printf("%#v\nstring           %#v\n\n", complexPerson, string(complexPersonBytes))

	complexPerson.Address.Street = "Main Street"
	complexPerson2Bytes, _ := json.Marshal(complexPerson)
	fmt.Printf("%#v\nstring           %#v\n\n", complexPerson, string(complexPerson2Bytes))
This entry was posted in golang, workday. Bookmark the permalink.

Leave a Reply