Unsupported JSON Type

243 views
Skip to first unread message

Ken MacKenzie

unread,
Aug 12, 2015, 9:48:07 PM8/12/15
to golang-nuts
OK keep in mind I am learning so I am sure dump mistakes abound.  But I am having a problem with this code.

package main


import (
 
"encoding/json"
 
"net/http"
 
"strconv"
 
"log"
)


func
GetJSONPosts (w http.ResponseWriter, r *http.Request) {
 somePosts
:= CreateSamplePosts
 enc
:= json.NewEncoder(w)
 w
.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w
.WriteHeader(http.StatusOK)
 err
:= enc.Encode(somePosts)
 
if err != nil {
 log
.Println(err)
 
}
/* for _, somePost := range somePosts() {
 err := enc.Encode(somePost)
 if err != nil {
 log.Println(err)
 }
 }*/

}


func
CreateSamplePosts () JSONPosts {
 posts
:= JSONPosts{}
 
for i := 0; i < 5; i++ {
 title
:= "Post " + strconv.Itoa(i+1)
 content
:= "This is content for post " + strconv.Itoa(i+1)
 post
:= JSONPost{Title: title, Content: content}
 posts
= append(posts, post)
 
}
 
return posts
}

package main


import (
 
"html/template"
)


type
Page struct {
   
Title string //`json:"title"`
   
Content template.HTML //`json:"content"`
   
PagePosts []Post
}


type
Pages []Page


type
Post struct {
   
Title string //`json:"title"`
   
Content template.HTML //`json:"content"`
}


type
Posts []Post


type
JSONPost struct {
   
Title string `json:"Title"`
   
Content string `json:"Content"`
}


type
JSONPosts []JSONPost


When I run this in the browser nothing shows.  The error printed at the console is:
2015/08/12 21:46:06 json: unsupported type: func() main.JSONPosts

Now note in the first section of code the commented part works.  Well sort of.  No errors and something is output but since it is doing each struct item piecemeal the json is missing the commas between items.  Been googling around and not been able to figure out what I am doing wrong.

Obviously there is more to this code in other pieces but the rest of it is more the routes and main program/server.

Ken

Kiki Sugiaman

unread,
Aug 12, 2015, 10:57:05 PM8/12/15
to golan...@googlegroups.com
A shot in the dark since you did not post a working code: did you try to
call the function from another package (outside main)?

Dustin

unread,
Aug 12, 2015, 11:24:45 PM8/12/15
to golang-nuts
someposts := CreateSamplePosts() 
You're missing the brackets and passing the function, not the result of calling the function.

Ken MacKenzie

unread,
Aug 12, 2015, 11:30:18 PM8/12/15
to golang-nuts
That solved it.  Excellent, thank you.

And that also teaches me how about assigning a function itself to a variable.

Ken
Reply all
Reply to author
Forward
0 new messages