How can I propagate deserialization errors to serde_json functions?

I'm trying to add my own domain invariant to serde_json's logic for deserializing arbitrary JSON values. The invariant is that if it is a Map, the key cannot be an empty string.

Here's what I have so far: Rust Playground

However, the current error returned by serde_json::from_str() just says "data did not match any variant of untagged enum Value". I understand why that is the case; untagged just means serde_json will try each variant, so I don't think it could correctly produce more specific errors than this.

That being said, is there any way to accomplish what I want without rewriting all of the implementation logic of serde_json::Value from scratch? I want any deserialization errors to include "Must not be empty" as well as (ideally) the location of the empty key in the JSON object (maybe a JSON path).

1 Like

The minimal change I could imagine is a TryFrom<serde_json::Value> impl for Value, and the implementing Deserialize in terms of that.

For better error locations, use serde_path_to_error.

3 Likes

Awesome, thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.