Skip to content

Commit f748439

Browse files
authored
[go] JSON deserialize Union fix (#1954)
Talked this through w/ @hellovai today, and this approach makes sense. Walks the union variants and just tries to deserialize until it is successful or fails completely. <!-- ELLIPSIS_HIDDEN --> ---- > [!IMPORTANT] > Implements JSON deserialization for union types in Go by attempting to unmarshal each variant until successful, with tests added for verification. > > - **Behavior**: > - Implements `UnmarshalJSON` for union types in `types-unions.go.j2` and `unions.go`. > - Attempts to unmarshal each variant until successful, otherwise returns an error. > - **Tests**: > - Adds test cases for `Union__float__bool` in `json_test.go` to verify round-trip serialization and deserialization. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for b0d83d7. You can [customize](https://app.ellipsis.dev/BoundaryML/settings/summaries) this summary. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent 8074631 commit f748439

3 files changed

Lines changed: 673 additions & 31 deletions

File tree

‎engine/language_client_codegen/src/go/templates/types-unions.go.j2‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,17 @@ func (u {{ union.name }}) MarshalJSON() ([]byte, error) {
6060
}
6161

6262
func (u *{{ union.name }}) UnmarshalJSON(data []byte) error {
63-
return fmt.Errorf("not implemented")
63+
var err error
64+
{% for variant in union.variants %}
65+
err = json.Unmarshal(data, &u.variant_{{ variant.0 }})
66+
if err == nil {
67+
u.variant = "{{ variant.0 }}"
68+
return nil
69+
} else {
70+
u.variant_{{ variant.0 }} = nil
71+
}
72+
{% endfor %}
73+
return fmt.Errorf("invalid union variant: %s", string(data))
6474
}
6575

6676
{% for variant in union.variants %}

0 commit comments

Comments
 (0)