Unmarshal JSON Array of arrays in Go

The JSON:

[
  {
    "type": "Car",
    "wheels": 4
  },
  {
    "type": "Motorcycle",
    "wheels": 2
  }
]

The Struct:

type Vehicle struct {
  Type   string
  Wheels int
}

The Unmarshaller:

func TestVehicleUnmarshal(t *testing.T) {
    response := `[{"type": "Car","wheels": 4},{"type": "Motorcycle","wheels": 2}]`

    var vehicles []Vehicle
    json.Unmarshal([]byte(response), &vehicles)

    assert.IsType(t, Vehicle{}, vehicles[0])
    assert.EqualValues(t, "Car", vehicles[0].Type)
    assert.EqualValues(t, 4, vehicles[0].Wheels)
    assert.EqualValues(t, "Motorcycle", vehicles[1].Type)
    assert.EqualValues(t, 2, vehicles[1].Wheels)
}

https://play.golang.org/p/5SfDH-XZt9J


Do I need to implement my own Unmarshaller for this?

Yes.

You're trying to unmarshal an array into a struct (Point), which means you need to tell the JSON unmarshaler how the array values map to the struct values.

Also note that your tags are incorrect in your Point definition. json tags refer to the key names, but arrays don't have keys (in JavaScript they can be accessed as if they do, but this isn't JavaScript). In other words, json:"0" will only work if your JSON looks like {"0":123}. If you implement your own unmarshaler, you can just get rid of those json tags.