Hacker News new | ask | show | jobs
by q3k 2070 days ago
It means sometimes you'll get:

    { foo: { bar: "baz" }}
and other times you'll get

    { foo: "something else" }
Good luck!
3 comments

Polymorphic JSON is such a PITA for strongly typed languages.

    var data map[string]interface{}
    //.. 
    switch t := data["foo"].(type) {
         case string:
         case interface{}
    }

imagine that for every key...
In my humble opinion, Golang is pretty verbose in a bad way when it comes to JSON. Rust and the crate serde_json are also strongly typed and it's a lot better.
Yeah, having done this, it's extremely verbose if you have all your error handling in there due to the verbosity of dealing with JSON and explicit return values instead of exceptions. By far my greatest annoyance is that []interface{} cannot be directly cast to []concreteType. Having to make a sized slice and type assert each value is annoying. Require validation of the values for even more "if err != nil" fun.

Many Go advocates seem to consider the verbosity a feature, because it's explicit and forbids any clever-but-confusing tricks.

How would you express deserializing these 'polymorphic JSON' objects using serde/Rust?
Using a rust enum I guess.
You're right, this does seem to work [1]. I wasn't aware that serde would attempt to deserialize multiple enum variants until something matches.

[1] - https://serde.rs/enum-representations.html#untagged

Yeah that's a rather common scheme out there so Serde does provide built-in support for this deserialisation. Probably better for deserialisation performances to use properly tagged enums, but if you don't have a choice Serde's got your back.

    { foo: { length: 1.7976931348623157e+308 } }
So, like Apple and in app payments then...