Is it possible to rename property keys while parsing? #1182
-
I am parsing input data with keys that follow one naming convention ("Full Name", "Email Address") , and I would like my parsed output to have keys that follow a different naming convention ("name", "emailAddress"). I am currently manually renaming properties before parsing, with code that looks something like this: const MemberSchema = v.object({
name: v.optional(v.string()),
emailAddress: v.pipe(v.string(), v.nonEmpty()),
});
export type Member = v.InferOutput<typeof MemberSchema>;
export function parseMember(record: Record): Member {
const member = {
name: record['Full Name'],
emailAddress: record['Email Address'],
};
return v.parse(MemberSchema, member);
} Does Valibot support mapping from one input key to a different output key in the schema? The solution I'm hoping for would look something like this imagined const MemberSchema = v.object({
name: v.pipe(v.getValueWithKey('Full Name'), v.optional(v.string())),
emailAddress: v.pipe(v.getValueWithKey('Email Address'), v.string(), v.nonEmpty()),
}); Edit: I know that this approach is also possible, but while it does move the renaming into the schema, it feels more verbose than my original implementation above: const MemberSchema = v.pipe(
v.record(v.string(), v.unknown()),
v.transform((record) => ({
name: record['Full Name'],
emailAddress: record['Email Address'],
})),
v.object({
name: v.optional(v.string()),
emailAddress: v.pipe(v.string(), v.nonEmpty()),
}),
); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey 👋 thank you for reaching out! Feel free to take a look at this issue. In the long run we will try to provide common transformations like |
Beta Was this translation helpful? Give feedback.
Hey 👋 thank you for reaching out! Feel free to take a look at this issue. In the long run we will try to provide common transformations like
toSnakeCaseKeys
out-of-the-box.