Can I use serde/serde_json serialize the location of a struct/field?

Can I use serde to deserialize from json/yaml not just a value, but the location (line number/column) that value was serialized at?

I'm writing a parsing system where the parsing itself is fairly straightforward, but there are additional business rules that are applied after parsing, and I'd like to be able to report an error back to the customer like "at line 71, reference to ID "x" that was not found in the document". Or "At line 1004, cannot nest an item of type X inside of type Y."

1 Like

The topic mentioned serialization, but the contents deserialization, assuming deserialization.

Serde does not automagically for deserializers, deserializers though can implement it.

There is an issue for this for serde-json here: Get line and column number on valid JSON? · Issue #637 · serde-rs/json · GitHub
The corresponding issue for yaml, the issue was closed: Support emitting spans when deserializing structures by Michael-F-Bryan · Pull Request #201 · dtolnay/serde-yaml · GitHub

Thanks… that seems to be what I need. It’s too bad that there isn’t a serde-generic version of this also since that could bridge serialization formats like json/yaml. I guess I could just use a forked serde-yaml though since it’s a superset of json.