2

I tried to "Unmarshal" json in golang, but it doesn't seem to be working. I get 0 printed out instead of 1. What am I doing wrong?

package main

import (
  "fmt"
  "encoding/json"
)

type MyTypeA struct {
  a int
}

func main() {
  var smthng MyTypeA
  jsonByteArray := []byte(`{"a": 1}`)
  json.Unmarshal(jsonByteArray, &smthng)
  fmt.Println(smthng.a)
}

1 Answer 1

4

Two problems with your code.

  1. You need to export fields or Marshal won't work, read about it here.
  2. Your package must be called main or func main won't be executed.

http://play.golang.org/p/lJixko1QML

type MyTypeA struct {
    A int
}

func main() {
    var smthng MyTypeA
    jsonByteArray := []byte(`{"a": 1}`)
    json.Unmarshal(jsonByteArray, &smthng)
    fmt.Println(smthng.A)
}
Sign up to request clarification or add additional context in comments.

1 Comment

oops, the foo was a copy paste error. I fixed it so that doesn't throw people off in the future. Thanks for the answer!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.