Skip to content

Feature request: add helper function to transform and pipe JSON strings to a custom schema #2893

Closed
@am29d

Description

@am29d

Use case

As proposed by @dreamorosi in #2892 it'd be great to extract the helper function from the docs to a dedicated export, so users can utilize it from the IDE instead of consulting the docs.

  • add helper function
  • add exports
  • add tests all applicable built-in schemas that can have JSON stringified payload
  • change parser docs how to use the helper function

Solution/User Experience

import { z, type ZodSchema } from 'zod';

const JSONStringified = (schema: ZodSchema) =>
    z
      .string()
      .transform((str, ctx) => {
        try {
          return JSON.parse(str);
        } catch (err) {
          ctx.addIssue({
            code: 'custom',
            message: 'Invalid JSON',
          });
        }
      })
      .pipe(schema);

export { JSONStringified };

Alternative solutions

No response

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

Labels

completedThis item is complete and has been merged/shippedfeature-requestThis item refers to a feature request for an existing or new utilityparserThis item relates to the Parser Utility

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions