Golang access contents of ViewResult


#1

I am trying to parse the result from querying a View in couchbase from Golang. I get the results back but i am unable to access the contents in doc. How do i access “dataContent” from response in my below example

b, err = couchbase.GetBucket(host, “default”, “test”)
b. View(“dummy”, “dummy”, map[string]interface{}{“stale”: false, “ascending”: true, “include_docs” : true, “start_k
ey” : 123 })
fmt.Println(*(res.Rows[0].Doc))

//Result
map[json:map[dataContent:test_data updated_at:1.413321701e+09] meta:map[expiration:0 flags:0 id:t:102 rev:2-00028830770939880000000000000000]]


#2

I’m not quite sure I understand the question. As you have already demonstrated from your example the field Doc contains the document content (only when include_docs is true). Further, the output shown as the result shows that it is a map containing two sections “json” and “meta”. Each of those is also a map. The json section contains two fields “dataContent” and “updated_at”.

The problem you may be facing is that is that Doc is type interface{}, but we see from the output that it is actually a map[string]interface{}. In Go you’d have to use a type assertion to verify this and access it (while avoiding a panic).

I would do something like:

doc, ok := *(res.Rows[0].Doc).(map[string]interface{})
if ok {
  dataContent = doc["dataContent"]
  // dataContent will also just be type interface{} if you expect it to be a string
  // you'll need another type assertion here to check/cast it to that
}

#3

Thanks very much. That did the trick!