npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chicane-ai/box-json-validation

v1.0.0

Published

Box JSONValidation para Chicane - validação de JSON e schema

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

  1. Validação de APIs: Verificar se respostas de API estão no formato esperado
  2. Configurações: Validar arquivos de configuração JSON
  3. Formulários: Validar dados de formulários antes do envio
  4. LLM Outputs: Validar saídas de modelos de linguagem
  5. 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:

  1. Fork o repositório
  2. Crie uma branch para sua feature
  3. Implemente suas mudanças
  4. Adicione testes
  5. Abra um Pull Request

📄 Licença

MIT License