Not quite sure how to access the value I'm interested in. What I have is response from my couchDB that looks like this:
response from couchDB in json format
What I am interested in is to get out the "name" and "phone" value using golang.
If I run this code, I at least get out the value of id or key:
package main
import(
"net/http"
"encoding/json"
"io/ioutil"
"fmt"
)
type rows struct{
Rows []info `json:"rows"`
}
type info struct{
Name string `json:"id"`
}
func main() {
resp, err := http.Get("http://localhost:5984/mydb/_all_docs?include_docs=true")
bytes, _ := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
var d rows
json.Unmarshal(bytes, &d)
fmt.Println(d)
}
So I tried doing it this way to get "name" for starter:
package main
import(
"net/http"
"encoding/json"
"io/ioutil"
"fmt"
)
type rows struct{
Rows []doc `json:"rows"`
}
type doc struct {
Values []info `json:"doc"`
}
type info struct{
Name string `json:"name"`
}
func main() {
resp, err := http.Get("http://localhost:5984/mydb/_all_docs?include_docs=true")
bytes, _ := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
var d rows
json.Unmarshal(bytes, &d)
fmt.Println(d)
}
But get this response: Output from script
I'm pretty new to golang but really want to learn how to build simple API with it, if there are any other ways to do this in golang please let me know
Here's how I would approach this problem
1) get the example json output and visit the website https://mholt.github.io/json-to-go/
Use this to automatically generate a struct that matches your data You may need to adjust what it makes to give you a "row" struct
2) Using the structs you have just devised, load the data with Unmarshall
3) dump the data with the %v Printf format to look at it and then work out how to get at the name and phone elements
You would have some example code here but your example data is in a picture so is time consuming to reproduce: sorry :/