Search code examples
arraysgointerfacetype-assertion

Is there a simpler way to decode this json in Go?


I am trying to parse some JSON from Jira to variables. This is using the go-jira package (https://godoc.org/github.com/andygrunwald/go-jira)

Currently I have some code to get the developer:

dev := jiraIssue.Fields.Unknowns["customfield_11343"].(map[string]interface{})["name"]

and team := jiraIssue.Fields.Unknowns["customfield_12046"].([]interface{})[0].(map[string]interface{})["value"]

to get the team they are a part of from.

Getting the team they are on is a bit gross, is there a cleaner way to get the team besides having to type assert, set the index, then type assert again?

Here is the complete json (modified but structure is same, its way too long):

{    
 "expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
   "id":"136944",
   "self":"https://jira.redacted.com/rest/api/2/issue/136944",
   "key":"RM-2506",
   "fields":{  
      "customfield_11343":{  
         "self":"https://redacted.com/rest/api/2/user?username=flast",
         "name":"flast",
         "key":"flast",
         "emailAddress":"[email protected]",
         "displayName":"first last",
         "active":true,
         "timeZone":"Europe/London"
      },
      "customfield_12046":[  
         {  
            "self":"https://jira.redacted.com/rest/api/2/customFieldOption/12045",
            "value":"diy",
            "id":"12045"
         }
      ],

   }

Thanks


Solution

  • The way I go about problems like this is:

    1. Copy some JSON with things I am interested in and paste it into https://mholt.github.io/json-to-go/
    2. Remove fields that aren´t of interest.
    3. Just read the data and unmarshal.

    You might end up with something like this given the two custom fields of interest, but you can cut the structure down further if you just need the name.

    type AutoGenerated struct {
        Fields struct {
            Customfield11343 struct {
                Self         string `json:"self"`
                Name         string `json:"name"`
                Key          string `json:"key"`
                EmailAddress string `json:"emailAddress"`
                DisplayName  string `json:"displayName"`
                Active       bool   `json:"active"`
                TimeZone     string `json:"timeZone"`
            } `json:"customfield_11343"`
            Customfield12046 []struct {
                Self  string `json:"self"`
                Value string `json:"value"`
                ID    string `json:"id"`
            } `json:"customfield_12046"`
        } `json:"fields"`
    }
    

    The effect you get is that all extra information in the feed is discarded, but you get the data you want very cleanly.