Write JSON of a struct to an http.ResponseWriter

4,617 views
Skip to first unread message

Frank Blechschmidt

unread,
Oct 17, 2012, 3:14:41 PM10/17/12
to golan...@googlegroups.com
Hey! :)

I try to implement a simple json api for http://datatables.net
For example I have a struct like that: Products {1 2 2 [{1 Malm 4 Pieces 258.7 20 258.7} {2 Brimnes 2 Pieces 180.7 10 180.7}]}
It has 3 ints and an array of structs of type ProductForSalesorder
type ProductJSON struct {
    sEcho  string
    iTotalRecords   int
    iTotalDisplayRecords int
    aaData []model.ProductForSalesorder
}
type ProductForSalesorder struct {
  ID int64
  Name string
  Quantity int64
  Unit string
  Price float64
  Shippingcost float64
  Promisedate string
}

How could i write to w http.ResponseWriter as JSON?

I tried:
jsonanswer, _ := json.Marshal(products)
fmt.Fprintf(w, "%s", jsonanswer)
and
enc := json.NewEncoder(w)
enc.Encode(products)

Nothing works for me so far :(

Best regards
Frank

jorelli

unread,
Oct 17, 2012, 3:24:19 PM10/17/12
to golan...@googlegroups.com
the second example should work fine.  Why are you discarding your error values?  You might want to look at those.  They typically contain error information.

and what's the output on the http response?  nothing?

Frank Blechschmidt

unread,
Oct 17, 2012, 3:32:06 PM10/17/12
to golan...@googlegroups.com
the http response:
{}

not really great :(

enc.Encode(products) givs me a nil error

Jeremy Wall

unread,
Oct 17, 2012, 3:37:19 PM10/17/12
to Frank Blechschmidt, golang-nuts
Which struct are you encoding? And how are you creating the products value?
> --
>
>

Frank Blechschmidt

unread,
Oct 17, 2012, 3:43:42 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
I have a struct called ProductJSON:
type ProductJSON struct {
    sEcho  string
    iTotalRecords   int
    iTotalDisplayRecords int
    aaData []model.ProductForSalesorder
}
which includes an array of a struct []ProductForSalesorder
type ProductForSalesorder struct {
  ID int64
  Name string
  Quantity int64
  Unit string
  Price float64
  Shippingcost float64
  Promisedate string
}

So my struct could look like: {1 2 2 [{1 Malm 4 Pieces 258.7 20 258.7} {2 Brimnes 2 Pieces 180.7 10 180.7}]}

An this struct should be converted into json for my responsewriter.

Frank Blechschmidt

unread,
Oct 17, 2012, 3:50:48 PM10/17/12
to golan...@googlegroups.com

Cole Mickens

unread,
Oct 17, 2012, 4:39:46 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
My guess is, the encoding works fine and it's encoding exactly what you've told it to. The `json` package can't see any fields of ProductJSON as ProductJSON does not export any of its fields. (Hint, try capitalizing sEcho, iTotal{Display,}Records, aaData).

Frank Blechschmidt

unread,
Oct 17, 2012, 5:03:10 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
Thanks, capitalizing works:
{"SEcho":"1","ITotalRecords":2,"ITotalDisplayRecords":2,"AaData":[{"ID":1,"Name":"Malm","Quantity":4,"Unit":"Pieces","Price":258.7,"Shippingcost":20,"Promisedate":"258.7"},{"ID":2,"Name":"Brimnes","Quantity":2,"Unit":"Pieces","Price":180.7,"Shippingcost":10,"Promisedate":"180.7"}]}

But I need the first char of SEcho, ITotalRecords, ITotalDisplayRecords and AaData in lowercase and 
"AaData": [{"ID":1,"Name":"Malm","Quantity":4,"Unit":"Pieces","Price":258.7,"Shippingcost":20,"Promisedate":"258.7"},{"ID":2,"Name":"Brimnes","Quantity":2,"Unit":"Pieces","Price":180.7,"Shippingcost":10,"Promisedate":"180.7"}]}
should look like 
  "aaData": [
    [
      "1",
      "Malm",
"4", "Pieces",
"258.7",
            "20",
            "258.7"
], [
      "2",
      "Brimnes",
"2", "Pieces",
"180.7",
            "10",
            "180.7"
]
]

How to do so?

Frank Blechschmidt

unread,
Oct 17, 2012, 5:16:48 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
Ok, I get the aaData array working, but I need the struct members in lowercase for datatables. How?

Andy Balholm

unread,
Oct 17, 2012, 5:21:56 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
On Wednesday, October 17, 2012 2:16:48 PM UTC-7, Frank Blechschmidt wrote:
Ok, I get the aaData array working, but I need the struct members in lowercase for datatables. How?

 You need to use struct tags:

type ProductJSON struct {
    Echo  string `json:"sEcho"`
    TotalRecords   int `json:"iTotalRecords"`
    TotalDisplayRecords int `json:"iTotalDisplayRecords"`
    Data []model.ProductForSalesorder `json:"aaData"`
}

Frank Blechschmidt

unread,
Oct 17, 2012, 5:35:03 PM10/17/12
to golan...@googlegroups.com, Frank Blechschmidt
Thanks, it's working now. You are the best :D

Cole Mickens

unread,
Oct 17, 2012, 10:42:46 PM10/17/12
to golan...@googlegroups.com
Hi Frank,

I'm glad my hint helped. You can always transform that data in javascript if you want as well, but you can also use the struct tags to output it straight out of Go. I tend to put struct tags on all the fields of my structs, but that also might have to do with my OCD regarding lowercase names in my json/javascript.

In the future, if you get stuck on json encoding/decoding, the docs for the json package are quite good: http://golang.org/pkg/encoding/json/ (watch out for the Example >) links, I miss them often when looking for help in the docs.
This blog post is more demonstrative: http://blog.golang.org/2011/01/json-and-go.html

Between those two links, I think your issues here, and ones you may run into soon, are discussed.

Best of luck,
Cole

Richard Varno

unread,
Jan 5, 2014, 4:43:52 PM1/5/14
to golan...@googlegroups.com
Thanks for the capitalizing hint!  Totally fixed my issue

cornel...@gmail.com

unread,
Jun 21, 2014, 7:07:50 PM6/21/14
to golan...@googlegroups.com, frab...@gmail.com
I'm trying to do something similar and I'm stuck on the similar problem. How did you solve the aaData problem so the JSON is formatted properly for DataTables?


On Wednesday, October 17, 2012 2:16:48 PM UTC-7, Frank Blechschmidt wrote:

Shawn Milochik

unread,
Jun 22, 2014, 11:05:14 AM6/22/14
to golan...@googlegroups.com
On Sat, Jun 21, 2014 at 7:07 PM, <cornel...@gmail.com> wrote:
I'm trying to do something similar and I'm stuck on the similar problem. How did you solve the aaData problem so the JSON is formatted properly for DataTables?



Use a JSON field tag to specify a different name when you marshal:

cornel...@gmail.com

unread,
Jun 22, 2014, 12:10:51 PM6/22/14
to golan...@googlegroups.com, Sh...@milochik.com
Hi Shawn, thanks for the reply. The JSON tags were already tagged, the problem was actually on the DataTables side, not on the Go JSON side. Go figure. 

Anyways, for anyone else who finds the same issues this can be solved in two ways. DataTables by default expects a 2D array so you can build that on the fly (which I find ugly) or just modify you initialization of DataTable() to accept your marshaled data as-is.



var table = $('#example').DataTable( 
    {
        ...
       "sAjaxSource": "/api/allfirmware",
        "columns": [
                {
                "class":          'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "make" },
            { "data": "model" },
            { "data": "interface" },
            { "data": "country" },
            { "data": "special" },
            { "data": "revision" }
        ],
    });
Reply all
Reply to author
Forward
0 new messages