1

I am trying to convert my struct "Sim" into JSON, after being filled with data.

When I print the var s, it shows correct information, when I print data, it shows blank.

How do I convert Struct to JSON?

Reduced Code Below:

type Sim struct { yr, ag, av, db, wd, st []int withdrawal []string } func main() { // Creating simulation var s Sim // Filling with data s = simulate(15000, 60, 65, 90, 2015, 10.0, 140000.0, true, s) // Converting to JSON, for transmission over web data, err := json.Marshal(s) if err != nil { fmt.Println(err) return } // Data is correct fmt.Println(s) // Prints: {} fmt.Println(string(data)) } 
6
  • 2
    This is possible the 300th question about JSON (un)marshaling with non-exported fields. Meta-question: Is really nobody able to find this information in the documentation of package encoding/json? Is this so complicated to find on SO? Why is this beeing asked over and over again? Commented Nov 25, 2015 at 8:53
  • Honestly, I read like 5 questions and it wasn't until directly after I posted mine, that I found one talking about the required Caps on it. I even watched a talk on it by Google Engineers, they used caps, but didn't explain the significance of that decision. Commented Nov 25, 2015 at 8:58
  • Also, I have written plenty of code in my life, while many languages use caps to denote meaning, I've never seen one strongly enforced like this. Commented Nov 25, 2015 at 9:17
  • 2
    It is the third page of the "Basics" chapter in the Go Tour: tour.golang.org/basics/3 . (And the Basics chapter is the first after the Welcome chapter.) The whole Tour covers almost everything needed to know and takes maybe two hours. Commented Nov 25, 2015 at 10:33
  • 1
    All languages have some seemingly arbitrary rules to learn. I could say it doesn't make sense that exported identifiers need to be redeclared in separate header files for some languages. Commented Nov 25, 2015 at 14:00

1 Answer 1

1

Fields in your structures starts with lower case so they are not marshalled to JSON. Make them start with upper case letter.

package main import "encoding/json" import "fmt" type Sim struct { Yr, Ag, Av, Db, Wd, St []int Withdrawal []string } func main() { // Creating simulation var s Sim // Converting to JSON, for transmission over web data, err := json.Marshal(s) if err != nil { fmt.Println(err) return } // Data is correct fmt.Println(s) // Prints: {} fmt.Println(string(data)) } 

Playground

JSON serialization in GO

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, you beat me to it, I just realized that. Thanks! (I'll accept in 3 min once timer allows)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.