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))
}
triunenature
  • 651
  • 2
  • 7
  • 23
  • 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? – Volker Nov 25 '15 at 08: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. – triunenature Nov 25 '15 at 08: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. – triunenature Nov 25 '15 at 09:17
  • 2
    It is the third page of the "Basics" chapter in the Go Tour: http://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. – Volker Nov 25 '15 at 10:33
  • Right, and I went through the tour when I started. But that didn't really click. It still doesn't make sense that they use caps to determine private v public methods. – triunenature Nov 25 '15 at 10:48
  • 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. – JimB Nov 25 '15 at 14:00

1 Answers1

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

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105