go - Marshalling empty map[string]interface{} results in "null" instead of nil -


i have problem go inserting "null" postgresql database's jsonb columns if try following, , structs property (in case of type map[string]interface{}) empty:

accessmembers, _ := json.marshal(c.accessmembers) 

doing test print outputs same value stored database:

fmt.println(string(accessmembers)) // equals string "null" 

the problem need - nil (not string, golang nil), when use in exec function below:

sqlstr := `update my_table set access_members=$1 id=$2;`  _, err := db.exec(sqlstr, accessmembers, c.id) 

it should equivalent (which works!!) of doing:

_, err := db.exec(sqlstr, nil, c.id) 

i tried lot of different workarounds, thought had work, didn't.

eg.

var accessmembers []byte  am, _ := json.marshal(c.accessmembers)  if string(am) != "null"{     accessmembers = }  sqlstr := `update my_table set access_members=$1 id=$2;`  _, err := db.exec(sqlstr, accessmembers, c.id) 

which results in following error: "pq: invalid input syntax type json"

i can't understand why not same, explicitly writing nil in exec functions parameter, since []byte must nil, right?

what doing wrong here? here's how had hoped work: http://play.golang.org/p/uolagfhhrl

answer:

var accessmembers interface{} = nil  if c.accessmembers != nil {     j, _ := json.marshal(c.accessmembers)     accessmembers = j } 

thanks thwd providing solution basically, , pointing out how database driver marshals nil differently, suggesting interface{} instead of []byte.

thanks donseba reminding me check if struct field exists before using resources marshal, string conversion , comparison, ought more expensive.

i can't understand why not same, explicitly writing nil in exec functions parameter, since []byte must nil, right?

nil has type. database driver marshals nil differently type map[string]interface{} or []byte interface{} (which type of second argument of db.exec). should able do:

var interface{} = nil  j, _ := json.marshal(c.accessmembers)  if string(j) != "null" {      = j }  sqlstr := `update content set access_members=$1 id=$2;`  _, err := db.exec(sqlstr, i, c.id) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -