Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: unmarshal uses the first struct in a union of structs #3474

Open
Feoramund opened this issue Apr 23, 2024 · 1 comment
Open

Comments

@Feoramund
Copy link
Contributor

Context

json.unmarshal seems to be ignoring alternative structs in a union, because if it doesn't find the fields it's looking for on the first struct variant it tries, it parses it as any value, skipping the other possibilities.

} else {
// allows skipping unused struct fields
// NOTE(bill): prevent possible memory leak if a string is unquoted
allocator := p.allocator
defer p.allocator = allocator
p.allocator = mem.nil_allocator()
parse_value(p) or_return
if parse_comma(p) {
break struct_loop
}
continue struct_loop
}

Odin:    dev-2024-04:2416380f3
OS:      Arch Linux, Linux 6.8.7-arch1-1
CPU:     12th Gen Intel(R) Core(TM) i7-12700K
RAM:     31916 MiB
Backend: LLVM 14.0.6

Expected Behavior

JSON unmarshalling to B instead of A, or some sort of error/advisory/workaround.

Current Behavior

Invalid type assertion from U to B, actual type: A

Failure Information (for bugs)

Steps to Reproduce

package main

import "core:encoding/json"

A :: struct {
    a: int,
}

B :: struct {
    b: string,
}

U :: union {
    rawptr,
    A,
    B,
}

main :: proc() {
    u: U

    error := json.unmarshal_string(`{"b": "Hellope"}`, &u)
    assert(error == nil)
    assert(u.(B).b == "Hellope")
}
@gingerBill
Copy link
Member

So this is actually tricky to handle correctly because it has to do a best fit search, and currently it does the "first fit" search. In the case other structs, a missing field might not be an error, so it just gets ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants