go – Grabbing value from Confluence JSON response-ThrowExceptions

Exception or error:

I’m trying to grab the ID field from the JSON response of a confluence page, that data looks like this:

`{"results":[{"id":"89425836","type":"page","status":"current","title":"string","extensions":{"position":"none"},"_links":{"webui":"/web/url","edit":"/pages/resumedraft.action?draftId=89425836","tinyui":"/x/rIdUBQ","self":"https://confluence.domain.org/rest/api/content/89425836"},"_expandable":{"container":"/rest/api/space/spaceName","metadata":"","operations":"","children":"/rest/api/content/89425836/child","restrictions":"/rest/api/content/89425836/restriction/byOperation","history":"/rest/api/content/89425836/history","ancestors":"","body":"","version":"","descendants":"/rest/api/content/89425836/descendant","space":"/rest/api/space/spaceName"}}],"start":0,"limit":25,"size":1,"_links":{"self":"https://confluence.domain.org/rest/api/content?spaceKey=spaceName&type=page&title=title","base":"https://confluence.domain.org","context":""}}`

I’ve been looking online and my code should be working but it’s not and I’m at a loss.

package main

import (
    "encoding/json"
    "net/http"
    "fmt"
    "io/ioutil"
)

type dataResponse struct {
    Id string `json:"id"`
}

func main() {

    var p dataResponse

    response, err := http.Get("https://confluence.domain.org/url/to/page/with/params"

    if err != nil {
       panic(err)
    } else {
      data, _ := ioutil.ReadAll(response.Body)
      json.Unmarshal(data, &p)
      fmt.Println(p.Id)
    }

   defer response.Body.Close()
}

But this isn’t returning anything. I think it has something to do with the id field being after the “results” but haven’t found a way to work with that. Edit: updated url, copied the debugging one by accident.

How to solve:

id is in an array of objects, inside results. To unmarshal a json document, your structure must match the document, that is:

type body struct {
  Results []dataResponse `json:"results"`
}

Then:

var doc body
json.Unmarshal(data, &doc)

You can get the id from:

doc.Results[i].Id

Leave a Reply

Your email address will not be published. Required fields are marked *