There is a code in which the data field with archival and non-archived json strings is taken from the database (1st row archive, 2nd and up to 5th json text, 6th archive. Using zlib, 1st, 6th line is output, but json strings are skipped. It is necessary It was displayed all together on the screen. I know that it is necessary to call json.Unmarshal again, but it still does not work. If anyone can, tell me. Thanks.

package main import ( "database/sql" "log" _"github.com/go-sql-driver/mysql" "compress/zlib" "bytes" "encoding/json" "fmt" "io/ioutil" ) func main() { db, err := sql.Open("mysql", "name:password@tcp(127.0.0.1:port)/database") if err != nil { panic(err.Error()) } defer db.Close() rows, err := db.Query(`SELECT data FROM user_stats ORDER BY created_at LIMIT 6`) if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var data []byte err := rows.Scan(&data) if err != nil { log.Fatal(err) } type UserStatsData struct { Revenue float64 `json:"r"` Gold int `json:"g"` } userStatsData := UserStatsData{} if err := json.Unmarshal(data, &userStatsData); err != nil { r, err := zlib.NewReader(bytes.NewReader(data)) if err != nil { log.Panicf("\nCannot read archive %v", err); } r.Close() output, _ := ioutil.ReadAll(r) fmt.Printf("%s\n", output) } 

}

  • The task is not clear. Date sql.Rows "json:\"d\"" - this is what you should do? json is not encoded or decoded directly into / from sql.Rows . - Ainar-G
  • This line is not needed, deleted. But in general, I understand what I need? - Sergio Hunter
  • Honestly, not so much. Show a sample of what data looks like and what you want in the end. - Ainar-G
  • There is a database in which the data field has many lines, both archival and text (json format), I need to decompress the data and display it all on the screen, it turns out to decompress, but the text data is not displayed along with the unarchived data. - Sergio Hunter Nov.

1 answer 1

in a piece

 if err := json.Unmarshal(data, &userStatsData); err != nil { r, err := zlib.NewReader(bytes.NewReader(data)) 

you have further processing only happens if an error occurred while reading json, i.e. if the data is archived.

I think you need something like this:

 userStatsData := UserStatsData{} if err := json.Unmarshal(data, &userStatsData); err != nil { r, err := zlib.NewReader(bytes.NewReader(data)) if err != nil { log.Panicf("\nCannot read archive %v", err); } r.Close() data, _ = ioutil.ReadAll(r) } fmt.Printf("%s\n", data) 

I'm here:

  1. Brought data output out of json validation condition
  2. When unpacking the archive, I substitute data from the database for unpacked data
  • Thank you very much, everything turned out to be much easier! - Sergio Hunter
  • Glad to help. If this is what you need - check the answer, and I will be pleased and other visitors will see that the issue is resolved. - rekby Nov.