Why is Couchbase/N1QL Escaping JSON before save?

Hi team!

I’m using the Go SDK for couchbase, and I have a JSON to append to a map (an existing document ) in couchbase using N1QL. Here’s how the JSON is derrived in the Go program:

sampleData := struct{
  ID       string  `json:"_id"`
  Amount   int     `json:"amount"`
}{
  "some_random_id",
  700
}

// converting Go struct to JSON
b, _ := json.Marshal(sampleData)


// using it in query
updoc := gocb.NewN1qlQuery("UPDATE bucket SET field = ARRAY_APPEND(field, $1) WHERE type = 'mytype' ")
_, err = Bucket.ExecuteN1qlQuery(updoc, []interface{}{string(b)})

The UPDATE query works, but when I checked the data in couchbase, I found out the JSON was escaped, the format is as this:

// the doc returned from couchbase-server 
{
  "field":[
     "{\"_id\":\"some_random_id\"}"
   ]
}

Any reason why its doing that? Cause I can’t Unmarshal it back to a struct when fetching again from the database.

cc @vsr1 @geraldss @ingenthr

Did u tried not doing string(b)

Yeah, I did that while passing the parameter for the query:

...
_, err = Bucket.ExecuteN1qlQuery(updoc, []interface{}{string(b)})

You want as array of objects not a array of strings (string inside string is escaped).

_, err = Bucket.ExecuteN1qlQuery(updoc, interface{}{b})

Oh… sorry I read your reply wrongly, I’ll try that now and revert

This didn’t work either, it instead saved the bytes as string example:

"eyJfaWQiOiI5ZDA4ZDY2Yi1lYjE3LTRkODItOWU5OC0xMzIwNGNiY2VkNDAiLCJ0eXBlIjoidHJhbnNhY3Rpb24iLCJyZWNpcGllbnRfaWQiOiIrMjM0MTIzNDU2Nzg5MCIsInRyYW5zYWN0aW9uX3R5cGUiOiJhZ2VudF90b191c2VyIiwic2VuZGVyX2nZW50IiwiYW1vdW50IjoxMjMsInRyYW5zYWN0aW9uX2ZlZSI6NSwiZGF0ZV9jcmVhdGVkIjoiMjAxOC0wNC0wMVQxMDo1MzoyMFoifQ=="

Try creating slice of sampleData and Marshall slice