dragon2025 2019-03-10 22:05
浏览 89
已采纳

如何通过JSON将所有记录正确显示为数组

For past 38 hours now I have been learning golang and coding this. This is what this code does.

The golang code below display two post records from database in an array via json. At the moment this is the json response am getting when I run the code and is okay for now..

[
{"id":"1",
"title":"Post Title 1 ",
"content":"post content 1."
},

{"id":"2",
"title":"post Title 2 ",
"content":"post content 2 "
}
]

At the moment, postlikeCount and postunlikeCount are not fetched in the array because they reside in another table.

If everything works fine, am supposed to get an array like this which contains everything like the sample below.

[
{"id":"1",
"title":"Post Title 1 ",
"content":"post content 1.",
"postlikeCount":"2",
"postunlikeCount":"1"},

{"id":"2",
"title":"post Title 2 ",
"content":"post content 2 ",
"postlikeCount":"4",
"postunlikeCount":"0"}
]

Now to get postlikeCount and postunlikeCount, I have implemented two sect of codings below which I passed within post for rows.next() functions.

// get postlikeCount based on userid and postid
var userid =5
var  postlikeCount int
err := db.QueryRow("SELECT COUNT(*) as postlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postlikeCount)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Number of postlikeCount rows are %s
",  postlikeCount)


// get postunlikeCount  based on userid and postid

var  postunlikeCount int
err1 := db.QueryRow("SELECT COUNT(*) as postunlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postunlikeCount)
if err1 != nil {
    log.Fatal(err1)
}

fmt.Printf("Number of postunlikeCount rows are %s
",  postunlikeCount)

The above two code works fine as I can Print their respective post like and unlike counts.

Here is my Issue:

When I tried to pass and append the postlikeCount and postunlikeCount parameters so that I can print them in json as per this line of code

posts = append(posts, post, postlikeCount,postunlikeCount)

It displays error

cannot postlikeCount (type int) as type post in append
cannot use postunlikeCount (type int) as type post in append

Does this error has to do with Struct function. Please can someone help me fix this. I need to pass postlikeCount and postunlikeCount as part of json as can be seen the complete array result above.

here is the full working code so far.

package main

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

import "net/http"
import "fmt"
import "encoding/json"
import "log"

var db *sql.DB
var err error

type Post struct {
Id  int
Title string
Content string  

}



func getRecordPage1(res http.ResponseWriter, req *http.Request) {

    if req.Method != "POST" {
        http.ServeFile(res, req, "getjsonRecord.html")
        return
    }


var (
post  Post
posts []Post
)

rows, err := db.Query("SELECT id,title,content FROM posts")
if err != nil {
            http.Error(res, "display error, unable to select records in json", 500)
            return
        }

for rows.Next() {

var postid =post.Id
var title = post.Title
var content = post.Content

fmt.Printf("%s is now %d
", postid, title, content)


// get postlikeCount based on userid and postid
var userid =5
var  postlikeCount int
err := db.QueryRow("SELECT COUNT(*) as postlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postlikeCount)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Number of postlikeCount rows are %s
",  postlikeCount)


// get postunlikeCount  based on userid and postid

var  postunlikeCount int
err1 := db.QueryRow("SELECT COUNT(*) as postunlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postunlikeCount)
if err1 != nil {
    log.Fatal(err1)
}

fmt.Printf("Number of postunlikeCount rows are %s
",  postunlikeCount)





rows.Scan(&post.Id, &post.Title, &post.Content)
posts = append(posts, post)

//like of code comment which causes issues
//posts = append(posts, post,postlikeCount,postunlikeCount)
}
defer rows.Close()


jsonResponse, jsonError := json.Marshal(posts)
if jsonError != nil {
fmt.Println(jsonError)
}

if jsonResponse == nil {
fmt.Println(jsonError)
} else {
res.Header().Set("Content-Type", "application/json")
res.Write(jsonResponse)
 fmt.Println("Json results displayed successfully")
}



}



func homePage(res http.ResponseWriter, req *http.Request) {
    http.ServeFile(res, req, "index.html")
}

func main() {
    db, err = sql.Open("mysql", "root:@/golang44")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    http.HandleFunc("/getjsonRecord", getRecordPage1)
    http.HandleFunc("/", homePage)
        fmt.Println("Listening on 127.0.0.1:8088")
    http.ListenAndServe(":8088", nil)
}
  • 写回答

1条回答 默认 最新

  • douchuxun4162 2019-03-10 22:48
    关注

    Add PostLikeCount and PostUnlikeCount to Post struct:

    type Post struct {
        Id              int
        Title           string
        Content         string
        PostLikeCount   int
        PostUnlikeCount int
    }
    

    After query "SELECT COUNT(*) as postlikeCount FROM postData ...":

    post.PostLikeCount = postlikeCount
    

    After query "SELECT COUNT(*) as postunlikeCount FROM postData ...":

    post.PostUnlikeCount = postunlikeCount
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?