Golang+Firebase: Parsing JSON Responses

There are some opensource SDKs for Firebase written in Golang but I haven’t used them. I had a small issue with parsing JSON response from Firebase where I had multiple objects stores in a path. Each object thas an ID and as such the JSON returned from Firebase uses fields with the IDs as the fieldname. When you want to parse this JSON and iterate over I found this method worked. It’s quick and simple.

For the following example objects returned by Firebase:

{
  "38472398235" : {
    "first": "Jack",
    "last": "Doe",
    "age": 50
  },
  "98897567345" : {
    "first": "Jane",
    "last": "Doe",
    "age": 40
  }
}

You can’t simply declare a struct and use Go’s simple but effective encoding/decoding mechanisms. The field names can’t be determined beforehand, however, we can use that idiom for the objects. So let’s define that struct.

type Person struct {
  First string `json:"first"`
  Last  string `json:"last"`
  Age   int    `json:"age"`
}

To allow us to parse those objects neatly we need to walk through the JSON and as we encounter fields that are objects we will decode the raw values for those fields.

// Let's assume we fetch some JSON identical to the structure of the example above.
var resp *http.Response
// ...

results := make(map[string]*json.RawMessage)
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&results)

people := make([]*Person, 0, 10)
for key, message := range results {
  person := &Person{}
  data, _ := message.MarshalJSON()
  if err := json.Unmarshal(data, person); err == nil {
    people = append(people, person)
  }
}

This worked well for my purpose. I wanted to create a map[string]Person with these values so I could iterate over later. If there’s a better way to parse this data in JSON would love to know.