Serde: how to ignore errors?

I am using serde to parse a JSON config. It's important for me that this never fails. Specifically, if a field can't be deserialized because the config is in the wrong format, I want to set this field to config::Default basically. Is it possible to do this with serde?

EDIT: naturally, I also want to collect the list of observed errors, and presnt the to the user

1 Like

You can call unwrap_or_default on the result you got from serde.

1 Like

That would set all fields to default values, and not only the problematic ones

Serde has field attributes to make this possible, either using the regular Default trait impl for the type or with a custom function.

1 Like

It only helps if attribute is missing, not if it has a wrong format.

Ie, something like this:

// config.rs
struct Config { value:  u32}

// config.json
{
  "value": "92"
}

The #[serde(deserialize_with = "path")] attribute can definitely take care of that too, as long as it's valid json.

Hm, indeed the attribute can help, if I annotate each field with the appropriate function, which also will have to duplicate my overall type's default... And I guess I won't get a list of errors that way?

Sure why not

1 Like

You might be able to use DeserializeSeed although I don't really know how it works.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.