# json: cannot unmarshal object into Go value of type []main.Foo

- **ID:** `go/json-cannot-unmarshal-object-into-go-value-of-type-slice`
- **Domain:** go
- **Category:** encoding_error
- **Verification:** ai_generated
- **Fix Rate:** 92%

## Root Cause

JSON input is an object (e.g., {}) but the target Go type is a slice, causing a type mismatch during unmarshaling.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Go 1.20 | active | — | — |
| Go 1.21 | active | — | — |
| Go 1.22 | active | — | — |

## Workarounds

1. **Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.** (90% success)
   ```
   Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.
   ```
2. **If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.** (85% success)
   ```
   If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
   ```
3. **Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }** (80% success)
   ```
   Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }
   ```

## Dead Ends

- **** — UseNumber() only affects number decoding, not structural type mismatches like object vs slice. (80% fail)
- **** — If the JSON is an array, wrapping in a struct will cause a different mismatch; the fix must match the actual JSON structure. (50% fail)
- **** — RawMessage just delays the error; you still need to unmarshal into the correct type later. (60% fail)
