Skip to content

Safe parse OpenAPI JSON schema #3046

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

Merged
merged 1 commit into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/little-wombats-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---

Safe parse OpenAPI JSON schema
25 changes: 18 additions & 7 deletions packages/react-openapi/src/OpenAPISchema.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export function OpenAPISchemaPropertiesFromServer(props: {
return (
<OpenAPISchemaProperties
id={props.id}
properties={JSON.parse(props.properties, retrocycle())}
properties={safeJSONParse(props.properties)}
context={props.context}
/>
);
Expand Down Expand Up @@ -172,12 +172,7 @@ export function OpenAPIRootSchemaFromServer(props: {
schema: string;
context: OpenAPIClientContext;
}) {
return (
<OpenAPIRootSchema
schema={JSON.parse(props.schema, retrocycle())}
context={props.context}
/>
);
return <OpenAPIRootSchema schema={safeJSONParse(props.schema)} context={props.context} />;
}

/**
Expand Down Expand Up @@ -465,3 +460,19 @@ function getDisclosureLabel(schema: OpenAPIV3.SchemaObject): string {

return schema.title || 'child attributes';
}

/**
* Safely parse a JSON string using retrocycle.
* If parsing fails, it falls back to standard JSON.parse.
*/
function safeJSONParse(jsonString: string) {
try {
return JSON.parse(jsonString, retrocycle());
} catch {
try {
return JSON.parse(jsonString);
} catch (fallbackError) {
throw new Error(`Failed to parse JSON string: ${fallbackError}`);
}
}
}