8000 v4: Schema key order is no longer preserved · Issue #4251 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

v4: Schema key order is no longer preserved #4251

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
crisog opened this issue Apr 21, 2025 · 4 comments
Closed

v4: Schema key order is no longer preserved #4251

crisog opened this issue Apr 21, 2025 · 4 comments
Labels

Comments

@crisog
Copy link
crisog commented Apr 21, 2025

In v3, when using z.object, the parsed return value kept the same key order as defined in the schema.

v4 changes how ordering works - it now seems to group required and optional properties separately while maintaining order within each group. This approach preserves some ordering, but IMO it's worse to v3's approach of preserving schema order, or to an alternative approach that would maintain the original object order.

This is a significant behavior change, and I think it should at least be documented in the changelog at https://v4.zod.dev/v4/changelog

v4:

const userSchema = z.object({
  name: z.string().optional(),
  email: z.email(),
  city: z.string().optional(),
  age: z.number().min(18),
});
{ email: 'alex@example.com', age: 25, name: 'Alex', city: 'Seattle' }
@scotttrinh
Copy link
Collaborator

If we want to change the ordering in v4, I'd suggest that we preserve the input order rather than the shape order. If we want to keep the v3 behavior (probably the most conservative approach given the ecosystem size), I'd support that!

@luis-herasme
Copy link

I think we should preserve the shape order to maintain compatibility with Zod 3.

@scotttrinh
Copy link
Collaborator

Confirmed that this seems to happen during the fastpass call: before the object is ordered like the shape, and after it is reordered.

@colinhacks
Copy link
Owner
colinhacks commented May 18, 2025

Fixed in #4396. An acceptable performance hit (~5%) to maintain backwards compat. I thought it would be much worse. Upgrade to latest beta for the fix.


PS: Note that you'll need to rewrite your v4 imports to "zod/v4" after upgrading; for more information, see #4371 for details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants
0