jsonsqlitegomartini

Error with JSON encoding in Martini


When I'm trying to get JSON data from my database, I get this:
{"time":"13:42:21 11.12.14",":":"Привет"}
{"time":"13:42:25 11.12.14",":":"Эй!"}

var time string 
var text string

type chatbetweenusers struct {
    Time string `json:"time"`
    Text string `json:":"text"`
    }

var buffer bytes.Buffer
    db, err := sql.Open("sqlite3", "./database.db"); if err != nil {
        log.Fatal(err)
    }; defer db.Close()

rows, err := db.Query("select time, text from messages;")
    if err != nil {
        log.Fatal(err) 
    } 
    defer rows.Close()


    for rows.Next() {
        // give a names for every column from query result
        err := rows.Scan(&time, &text)
        if err != nil {
            log.Fatal(err)
        }
        // add strings to struct
        chatitem := &chatbetweenusers{time, text}
        log.Println(chatitem)

        // format it to JSON!
        b, err := json.Marshal(chatitem)
        // conver JSON into string to return from Martini
        s := string(b[:])
        buffer.WriteString(s)
    }

return buffer.String()
})

And when I'm trying to get other data from database, I get this:
{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}

var text string
var user1 string

type chatbetweenusers struct {
    Text string `json:":"text"`
    User1 string `json:":"user1"`
    }

var buffer bytes.Buffer
    db, err := sql.Open("sqlite3", "./database.db"); if err != nil {
        log.Fatal(err)
    }; defer db.Close()

rows, err := db.Query("select text, user1 from messages;")
    if err != nil {
        log.Fatal(err) 
    } 
    defer rows.Close()


    for rows.Next() {
        // give a names for every column from query result
        err := rows.Scan(&text, &user1)
        if err != nil {
            log.Fatal(err)
        }
        // add strings to struct
        chatitem := &chatbetweenusers{text, user1}
        log.Println(chatitem)

        // format it to JSON!
        b, err := json.Marshal(chatitem)
        // conver JSON into string to return from Martini
        s := string(b[:])
        buffer.WriteString(s)
    }

return buffer.String()
})

What happens when I composite other data in JSON? I tried all that is possible, but this is doesn't work properly.


Solution

  • Consider the way you define your structures.

    In the first case:

    type chatbetweenusers struct {
        Time string `json:"time"`
        Text string `json:":"text"`
    }
    

    The syntax of the tag associated to Text is wrong. It should be:

        Text string `json:"text"`
    

    In the second case:

    type chatbetweenusers struct {
        Text string `json:":"text"`
        User1 string `json:":"user1"`
    }
    

    The syntax associated to both tags is wrong. They should be:

        Text string `json:"text"`
        User1 string `json:"user1"`
    

    Here is a playground example: https://play.golang.org/p/rirtTsTVWT