Converts a regular JSON Schema to a compatible OpenAPI 3.0.X Schema Object
npm install json-schema-for-openapi$ref. I have removed my own poor implementation of de-referencing JSON schemas since there are libraries that can do it better than I can.
json
{
"type": "object",
"properties": {
"example": {
"type": "array",
"items": [
{
"type": "string"
}
]
}
}
}
`
To:
`json
{
"type": "object",
"properties": {
"example": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
`
At the moment, this library cannot handle more than one item in the array, and so will default to using the first item only.
$3
This will convert a schema of:
`json
{
"type": "object",
"properties": {
"example": {
"type": ["string", "number"]
}
}
}
`
To:
`json
{
"type": "object",
"properties": {
"example": {
"oneOf": [
{
"type": "string"
},
{
"type": "number"
}
]
}
}
}
`
Where an array contains null, it will now set nullable against all types:
`json
{
"type": "object",
"properties": {
"example": {
"type": ["string", "number", "null"]
}
}
}
`
To:
`json
{
"type": "object",
"properties": {
"example": {
"oneOf": [
{
"type": "string",
"nullable": true
},
{
"type": "number",
"nullable": true
}
]
}
}
}
`
$3
This will convert a schema of:
`json
{
"type": "object",
"properties": {
"example": {
"type": "string",
"const": "Surburbia"
}
}
}
`
To:
`json
{
"type": "object",
"properties": {
"example": {
"type": "string",
"enum": ["Surburbia"]
}
}
}
`
$3
OpenAPI 3.0.X does not allow for null as a type, so will convert a schema of:
`json
{
"type": "object",
"properties": {
"example": {
"type": "null"
}
}
}
`
To:
`json
{
"type": "object",
"properties": {
"example": {
"nullable": true
}
}
}
`
$3
This will convert the "default": value to the relevant type. A String to a String, a Number/Integer to a number/Integer, a Boolean to a Boolean and try to manipulate an Object or an Array to either an Object or an Array
$3
This will try to convert "dependencies":, "dependentRequired": and "dependentSchemas": to a valid "allOf" in the case of a "dependentSchemas" or an "anyOf": schema in the case of a "dependentRequired".
$3
It will try to convert an If/Then/Else schema statement to a valid "OneOf" schema.
Installation and Usage:
Install via npm: npm install json-schema-for-openapi.
And use as a Factory like:
`js
const ConvertorFactory = require("json-schema-for-openapi");
const jsonSchema = {
$schema: "http://json-schema.org/draft-04/schema#",
title: "JSON API Schema",
description:
"This is a schema for responses in the JSON API format. For more, see http://jsonapi.org",
type: "object",
properties: {
errors: {
type: "object",
},
},
};
const convertedSchema = ConvertorFactory.convert(jsonSchema, "main");
`
which will output:
`json
{
"schemas": {
"main": {
"title": "JSON API Schema",
"description": "This is a schema for responses in the JSON API format. For more, see http://jsonapi.org",
"type": "object",
"properties": {
"errors": {
"type": "object"
}
}
}
}
}
``