Is there a simple way to convert data base rows to JSON in Golang

I'm dealing with the same issue, as far as my investigation goes it looks that there is no other way.

All the packages that I have seen use basically the same method

Few things you should know, hopefully will save you time:

  • database/sql package converts all the data to the appropriate types
  • if you are using the mysql driver(go-sql-driver/mysql) you need to add params to your db string for it to return type time instead of a string (use ?parseTime=true, default is false)

You can use tools that were written by the community, to offload the overhead:

  • A minimalistic wrapper around database/sql, sqlx, uses similar way internally with reflection.

  • If you need more functionality, try using an "orm": gorp, gorm.

If you interested in diving deeper check out:

  • Using reflection in sqlx package, sqlx.go line 560
  • Data type conversion in database/sql package, convert.go line 86

Tags:

Go