简体   繁体   中英

Converting string to json in Go

I am new to Go, and was learning to setup a http server. What i am trying to do is return a json output of 10 movies in my sql database. But the resulting output isn't in json. I checked the output with online json formatters, and the output was in json format.

I tried json.Marshall as well as json.Encode, but both are not giving the desired results.

type movie_list struct {
    Page int `json:"Page"`
    Results []movie `json:"Results"`
}
type movie struct {
    Id      int `json:"Id"`
    Title   string `json:"Title"`
    Language    string `json:"Language"`
    Release_date string `json:"Release_date"`
    Poster_path string `json:"Poster_path"`
    Background_path string `json:"Background_path"`
    Overview string `json:"Overview"`
    Genre_ids string `json:"Genre_ids"`
}
rows,err:=db.Query("select * from movies limit 10")

         if err!=nil{
            fmt.Println(err)
         }

         var list movie_list
         var tag movie

         for rows.Next(){

             err:=rows.Scan(&tag.Id,&tag.Title,&tag.Language,&tag.Release_date,&tag.Poster_path,&tag.Background_path,&tag.Overview,&tag.Genre_ids)
             if err != nil {
             fmt.Println(err)
            }

            list.Results = append(list.Results,tag)
         }

json.NewEncoder(w).Encode(list) 

The ouput in postman - 在此处输入图像描述

The formatted output - 在此处输入图像描述

my entire code is as follows (for reference)

package main

import (
    "fmt"
    "log"
    "net/http"
    "encoding/json"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    "github.com/davecgh/go-spew/spew"
)


func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/movie/top_rated", returnSingleArticle)
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}
type movie_list struct {
    Page int `json:"Page"`
    Results []movie `json:"Results"`
}
type movie struct {
    Id      int `json:"Id"`
    Title   string `json:"Title"`
    Language    string `json:"Language"`
    Release_date string `json:"Release_date"`
    Poster_path string `json:"Poster_path"`
    Background_path string `json:"Background_path"`
    Overview string `json:"Overview"`
    Genre_ids string `json:"Genre_ids"`
}


func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
    //vars := mux.Vars(r)
    //key := vars["id"]

    db, err := sql.Open("mysql", "root:72574484@tcp(127.0.0.1:3306)/PicturePerfect")
             if err != nil {
                 fmt.Println(err)
                 }else{
                 fmt.Println("Connection Established")
             }
    rows,err:=db.Query("select * from movies limit 10")

         if err!=nil{
            fmt.Println(err)
         }

         var list movie_list
         var tag movie

         for rows.Next(){

             err:=rows.Scan(&tag.Id,&tag.Title,&tag.Language,&tag.Release_date,&tag.Poster_path,&tag.Background_path,&tag.Overview,&tag.Genre_ids)
             if err != nil {
             fmt.Println(err)
            }
            fmt.Println(tag.Id)
            s2, _ := json.Marshal(tag)
            list.Results = append(list.Results,tag)
         }

        err = rows.Err()
        if err != nil {
            fmt.Println(err)
        }

        defer db.Close()


            //fmt.Fprintf(w, "Hello, %q\n", list.Results[3])
            json.NewEncoder(w).Encode(list) 
            spew.Dump(list)
            //fmt.Fprintf(w, "given lamguage, %q\n", tag.Poster_path)



}

func main() {
    handleRequests()

}

The problem is that the response content-type header is not application/json. Fix by setting the header before writing the body.

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(list) 

If the content type is not specified by the application, then the net/http server calls http.DetectConentType to set the content type in the response header. The function does not detect JSON and defaults to text/plain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM