@chicane-ai/box-json-validation
v1.0.0
Published
Box JSONValidation para Chicane - validação de JSON e schema
Maintainers
Readme
Chicane Box: JSONValidation
| Developed by | Chicane Team | | --- | --- | | Date of development | Jan 2024 | | Validator type | Format | | Blog | Chicane Blog | | License | MIT | | Input/Output | Input |
Box para validação de JSON e schemas no Chicane. Suporta validação de sintaxe JSON, estrutura de dados e schemas personalizados.
🚀 Características
- ✅ Validação de sintaxe JSON: Verifica se a string é um JSON válido
- ✅ Validação de schema: Suporte completo a schemas JSON Schema
- ✅ Comentários: Suporte opcional a comentários em JSON
- ✅ Modo estrito: Validação rigorosa de propriedades
- ✅ Múltiplos tipos: object, array, string, number, boolean, null
- ✅ Validações avançadas: regex, enum, min/max values, required fields
📦 Instalação
cd box-json-validation
npm install
npm run build🎯 Uso Básico
Validação de sintaxe JSON
import { SafetyCar, OnFailAction } from '@chicane-ai/core';
import { JSONValidation } from '@chicane-ai/box-json-validation';
const validator = new SafetyCar().use(
new JSONValidation(),
{},
OnFailAction.EXCEPTION
);
// JSON válido
const result1 = validator.validate('{"name": "João", "age": 30}');
console.log(result1.valid); // true
// JSON inválido
try {
validator.validate('{"name": "João", "age": 30,}'); // vírgula extra
} catch (error) {
console.log(error.message); // "Invalid JSON syntax: ..."
}Validação com schema
import { JSONValidation, JSONSchema } from 'chicane/box-json-validation';
const userSchema: JSONSchema = {
type: 'object',
properties: {
name: {
type: 'string',
minLength: 2,
maxLength: 50
},
age: {
type: 'number',
minimum: 0,
maximum: 150
},
email: {
type: 'string',
pattern: '^[^@]+@[^@]+\\.[^@]+$'
},
active: {
type: 'boolean'
}
},
required: ['name', 'age', 'email']
};
const validator = new SafetyCar().use(
new JSONValidation(),
{ schema: userSchema, strict: true },
OnFailAction.REFRAIN
);
const validUser = {
name: "João Silva",
age: 30,
email: "[email protected]",
active: true
};
const result = validator.validate(validUser);
console.log(result.valid); // true🔧 Configurações
JSONValidationConfig
interface JSONValidationConfig {
schema?: JSONSchema; // Schema para validação
strict?: boolean; // Modo estrito (rejeita propriedades extras)
allowComments?: boolean; // Permite comentários em JSON
message?: string; // Mensagem de erro personalizada
}JSONSchema
interface JSONSchema {
type?: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null';
properties?: Record<string, JSONSchema>; // Para objetos
required?: string[]; // Propriedades obrigatórias
items?: JSONSchema; // Para arrays
minItems?: number; // Tamanho mínimo do array
maxItems?: number; // Tamanho máximo do array
minLength?: number; // Comprimento mínimo da string
maxLength?: number; // Comprimento máximo da string
pattern?: string; // Regex para string
enum?: any[]; // Valores permitidos
minimum?: number; // Valor mínimo para número
maximum?: number; // Valor máximo para número
}📝 Exemplos
Validação de Array
const productSchema: JSONSchema = {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string', minLength: 1 },
price: { type: 'number', minimum: 0 },
category: {
type: 'string',
enum: ['electronics', 'clothing', 'books', 'food']
}
},
required: ['id', 'name', 'price']
};
const arraySchema: JSONSchema = {
type: 'array',
minItems: 1,
maxItems: 10,
items: productSchema
};
const validator = new SafetyCar().use(
new JSONValidation(),
{ schema: arraySchema },
OnFailAction.EXCEPTION
);JSON com Comentários
const jsonWithComments = `
{
// Este é um comentário
"name": "Maria",
"age": 25,
/* Comentário de múltiplas linhas */
"city": "São Paulo"
}
`;
const validator = new SafetyCar().use(
new JSONValidation(),
{ allowComments: true },
OnFailAction.EXCEPTION
);
const result = validator.validate(jsonWithComments);Validação de String
const stringSchema: JSONSchema = {
type: 'string',
minLength: 5,
maxLength: 100,
pattern: '^[A-Za-z\\s]+$' // Apenas letras e espaços
};
const validator = new SafetyCar().use(
new JSONValidation(),
{ schema: stringSchema },
OnFailAction.REFRAIN
);
const result = validator.validate("Joao Silva");🎯 Casos de Uso
- Validação de APIs: Verificar se respostas de API estão no formato esperado
- Configurações: Validar arquivos de configuração JSON
- Formulários: Validar dados de formulários antes do envio
- LLM Outputs: Validar saídas de modelos de linguagem
- Data Migration: Verificar integridade de dados durante migrações
🔍 Mensagens de Erro
O box fornece mensagens de erro detalhadas:
- Sintaxe JSON: "Invalid JSON syntax: [detalhes do erro]"
- Tipo incorreto: "Expected [tipo], got [tipo atual]"
- Propriedade obrigatória: "Missing required property: [nome]"
- Propriedade inesperada: "Unexpected property: [nome]"
- Validação de string: "String must be at least [n] characters long"
- Validação de número: "Number must be at least [n], got [valor]"
- Validação de array: "Array must have at least [n] items, got [atual]"
🤝 Contribuindo
Para contribuir com este box:
- Fork o repositório
- Crie uma branch para sua feature
- Implemente suas mudanças
- Adicione testes
- Abra um Pull Request
📄 Licença
MIT License
