Golang解析JSON响应

total Go newbie here, I am trying to parse response from an LDAP service that has the following structure

 {
      "isMemberOf": [
       “cn=group1,ou=groups,dc=example,dc=domain,dc=com",
       “cn=group2,ou=groups,dc=example,dc=domain,dc=com",
       "cn=.............................................,
       "cn=.............................................
       ]
    }

I need to gather all the cn= values ex: group1, group2 in to an []string like [group1,group2] or a struct.

As I said I am a total newbie to Go and would appreciate any pointers on how to achieve the above.

    struct type UserGroups struct {
        IsMemberOf []string `json:"isMemberOf"`
    }
//part of main code 
//receive the response from the service
     body, err := ioutil.ReadAll(res.Body)
        if err != nil {
           panic(err.Error())
        }

      s, err := getUserGroups([]byte(body))
     fmt.Println(s.IsMemberOf[0])


//end main code
//function to read user groups
   func getUserGroups(body []byte) (*UserGroups, error) {
    var s = new(UserGroups)
    err := json.Unmarshal(body, &s)
    if(err != nil){
        fmt.Println("whoops:", err)
    }
    return s, err
    }

//output cn=group1,ou=groups,dc=example,dc=domain,dc=com

I guess I could find the length of occurance of cn= something like this

count :=strings.Count(string(body),"cn=")

then use that count to go over the array above but still will not get me the array I want to have without some extra logic. I am missing the way to do this

appreciate if there somebody can point to a better alternate to do this.

thanks kris

First, you need to parse json encoded data.

import "encoding/json"

data := []byte(`
{
  "isMemberOf": [
    "cn=group1,ou=groups,dc=example,dc=domain,dc=com",
    "cn=group2,ou=groups,dc=example,dc=domain,dc=com",
    "cn=.............................................,
    "cn=.............................................
  ]
}
`)

var input struct {
    Items []string `json:"isMemberOf"`
}

err := json.Unmarshal(data, &input)
if err != nil {
    panic(err)
}

The next step is to parse each individual LDAP filter. You could use a regexp for your use case.

import "regexp"

var re = regexp.MustCompile("cn=([a-z0-9]+)")

commonNames := make([]string, len(input.Items))
for i, filter := range input.Items {
  commonNames[i] = re.FindAllString(filter, 1)[0]
}

// commonNames has the values you want

Unfortunately LDAP search filters can have fancy syntax so you may need to implement a proper parser. Here's one in ruby for example.