Update raise_on_unknown_json_key
flag to raise a more helpful error for debugging purposes
#44
Labels
enhancement
New feature or request
good first issue
Good for newcomers
Great To Have!
Important / Worth Addressing
help wanted
Extra attention is needed
self-created
Opened by me!
Description
I want to update the
UnknownJSONKey
exception that gets raised when theraise_on_unknown_json_key
flag is enabled to include a list of all the unknown JSON keys, rather than only the first such unknown key in the JSON object.I also want to update the error raised to include a resolution message, with more developer-friendly details on the suggested dataclass fields to add to to the model, to resolve the issue. I envision this will be really helpful for others -- at least, I found myself needing such a feature when I was attempting to parse a (not well-documented) API response from a web service myself recently.
What I Did
Consider this simple, but rather contrived, example:
Here's the error I currently get:
This is of course expected behavior, since we enabled the
raise_on_unknown_json_key
flag in the Meta config.The problem here, however, is that there are multiple fields in the JSON object that are missing from the dataclass schema. It would be very helpful if we had an output that listed out all those unknown JSON keys, along with an auto-generated dataclass schema with the lines that should be added to the model, the last of which I imagine will be super helpful when designing a model that would be expected to specifically match 1:1 to an API output.
For example, this is a sample of the output I might expect:
Notes
There's in fact a (somewhat) trivial approach. We can use a localized import from
dataclass_wizard.wizard_cli.PyCodeGenerator
to generate the desired dataclass schema. Also need to ensure to strip out the fields that already exist in the dataclass before calling this method. Something like this:The text was updated successfully, but these errors were encountered: