-1

I am trying to embed multiple objects inside a slice, so I can later export them as JSON. The JSON should look something like this:

[
   {
       name: "Nginx"
       version: "1.9"
   },
   {
       name: ircd-hybrid"
       version: "8.2"
    }
]

So far I have this struct in Go:

type response struct {
    application []struct {
        name        string
        version     string
    }
}

Now (I'm not even sure if the struct is correct), I'm trying to access it this way (again, not sure if this is correct):

   var d response
   d[0].name = "Nginx"
   d[0].version = "1.9"

And so on and so forth. However, it is not working, so I assume I went wrong somewhere. I just don't know where.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
JacksGT
  • 131
  • 8
  • 1
    possible duplicate of [Converting Go struct to JSON](http://stackoverflow.com/questions/8270816/converting-go-struct-to-json) – JimB Jul 16 '15 at 19:25
  • You are not that far though, here's a simple playground code to help you http://play.golang.org/p/6IvVM3bzDU – Twisted1919 Jul 16 '15 at 19:31

1 Answers1

0

The form of your 'model' (the struct in Go in this case) isn't quite right. You really just want this;

type application struct {
        Name        string `json:"name"`   // gotta uppercase these so they're exported 
        Version     string `json:"version"` // otherwise you can't marshal them
    }
apps := []application{
     application{Name:"Windows", Version:"10"}
}
app := application{Name:"Linux", Vesion:"14.2"}
apps = append(apps, app)

The json opens with [ meaning it is just an array, there is no enclosing object. If there were you would want another type with an application array ( []application ) property. To add items to that array you can use append or initialize it with some instance using the 'composite literal' syntax.

EDIT: I added some annotations so the json produced will have lower cased names like in your example. If a property isn't exported in Go other libraries like encoding/json won't be able to use it.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • Thanks for the tip about 'uppercase', you just solved another problem of mine :-) How can I access the slice / object? apps[0].Name gave me a "index out of range" error – JacksGT Jul 16 '15 at 19:27
  • @JacksGT that was the comment about append or composite literal for initilization, I'll update with an example of each. – evanmcdonnal Jul 16 '15 at 19:37