Sunday, March 27, 2016

initialize data structure and convert it to a JSON string

initialize data structure and convert it to a JSON string

package main

import (
  "fmt"
  "os"
  "encoding/json"
)

type Item struct {
  ItemName string
  ItemPrice int
}

type MyOrder struct {
  Status bool
  CustomerName string
  ItemArr []Item
}

func main() {
  item0 := Item {
    ItemName: "Computer",
    ItemPrice: 90,
  }
  item2 := Item { ItemName: "Motherboard", ItemPrice: 92, }
  item3 := Item { ItemName: "Hard drive", ItemPrice: 93, }
  item4 := Item { ItemName: "Mouse", ItemPrice: 94, }
  item5 := Item { ItemName: "Monitor", ItemPrice: 95, }
  item6 := Item { ItemName: "Book", ItemPrice: 96, }
  item7 := Item { ItemName: "Desk", ItemPrice: 97, }
  item8 := Item { ItemName: "Door", ItemPrice: 98, }
  item9 := Item { ItemName: "Car", ItemPrice: 99, }

  order1 := MyOrder {
    Status: true,
    ItemArr: []Item{item0, Item {ItemName: "Pen", ItemPrice: 91}}, // initialize with two items.
  }

  order1.CustomerName = "Jun"

  // first way of appending the items to the ItemArr slice.
  order1.ItemArr = append(order1.ItemArr, item2, item3)

  // second way of appending the items to the ItemArr slice.
  // The three dots is called variadic parameter / Ellipsis meaning unpack this slice into a set of variadic arguments.
  order1.ItemArr = append(order1.ItemArr, []Item{item4, item5}...)

  // third way of appending the items to the ItemArr slice.
  itemArr := []Item{item6, item7}
  order1.ItemArr = append(order1.ItemArr, itemArr...)

  // fourth way of appending the items to the ItemArr slice.
  order1.ItemArr = append(order1.ItemArr, item8)
  order1.ItemArr = append(order1.ItemArr, item9)

  encoder := json.NewEncoder(os.Stdout) //output to screen

  if err := encoder.Encode(order1); err != nil {
    fmt.Println(err)
  }
}

No comments: