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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥20 如何利用C语言实现用最小二乘法选配两个经验公式
    • ¥50 vue-codemirror如何对指定行 指定位置的 字符进行背景颜色或者字体颜色的修改?
    • ¥15 有人会思科模拟器嘛?
    • ¥30 遇到一个的问题,请教各位
    • ¥20 matlab报错,vflux计算潜流通量
    • ¥15 我该如何实现鼠标按下GUI按钮时就执行按钮里面的操作的方法
    • ¥15 关于#硬件工程#的问题:我这边有个锁相环电路没有效果
    • ¥15 20款 27寸imac苹果一体机装win10后,蓝牙耳机和音响放歌曲卡顿断断续续.
    • ¥15 VB.NET 父窗体调取子窗体报错
    • ¥15 python海龟作图如何改代码使其最后画出来的是一个镜像翻转的图形