Closed sailingwithsandeep closed 6 months ago
@sailingwithsandeep Hi,
Is it possible to convert typebox schema into JSON Schema?
All TypeBox types are valid Json Schema, so you don't need to convert them...they already are Json Schema.
const T = Type.Object({ // const T = {
x: Type.Number(), // type: 'object',
y: Type.Number(), // required: ['x', 'y', 'z'],
z: Type.Number() // properties: {
}) // x: { type: 'number' },
// y: { type: 'number' },
// z: { type: 'number' }
// }
// }
console.log(T) // This logs the schema object above (shows the Json Schema properties)
I found one package for it e.g. fast-json-stringify.
This is a fast serialization library maintained by the Fastify organization. It's used to accelerate serialization (stringify) of JavaScript objects to Json. It works by accepting a Json Schema, which it uses to generate fast serialization code for values matching that schema.
You can use TypeBox with this library.
import fastJson from 'fast-json-stringify'
import { Type } from '@sinclair/typebox'
// from: https://github.com/fastify/fast-json-stringify?tab=readme-ov-file#example
const stringify = fastJson(Type.Object({
firstName: Type.String(),
lastName: Type.String(),
age: Type.Integer(),
reg: Type.String()
}))
console.log(stringify({
firstName: 'Matteo',
lastName: 'Collina',
age: 32,
reg: /"([^"]|\\")*"/
}))
Is there way to extract this in typebox only??
Fast data encoding (like fast-json-stringify
) has been considered before, but likely won't be added to TypeBox. The reason for not including it mostly comes from not being able to provide an equally fast decode (parse
), as well as there being multiple ways to decode/encode data.
For such a feature to be included, Id ideally want Json, MsgPack, CBOR and possible XML encoding options for the library, as well as extremely fast encode/decode derived from schematics. I think given the nature of what would need to be achieved, it feel it's better to try achieve it outside of TypeBox as a separate specific serialization library.
Hope this helps! S
@sailingwithsandeep Heya,
Hey, might close out this issue. If you have any follow up questions, feel free to ping on this thread
Cheers! S
Thanks for the quick reply.
All TypeBox types are valid Json Schema, so you don't need to convert them...they already are Json Schema.
As suggested in readme as well. But i was getting empty string when i tried typbox schema with this library that's why i was wondering that you guys are saying this is json schema... So, i was little confused and landed here.
Maybe i was doing something wrong! Sorry for troubling you @sinclairzx81.
Cheers.
Sorry if i sound rookie here, But is it possible to convert typebox schema into JSON Schema? I found one package for it e.g. fast-json-stringify. Is there way to extract this in typebox only??