Skip to content

Repository files navigation

JavaScript Object Praser

VersionLast commitLicense

@dmitrytavern/object-parser - is a library for object validation that takes the original object and its schema, and then checks all object properties for existence and typing, can call a custom validator and assign a default value.

The library supports typescript and has smart autocomplete for checked objects.

It has no external dependencies and weighs ~7KiB compressed without gzip and ~3KiB with.

A quick example

npm install --save @dmitrytavern/object-parser
importparserfrom'@dmitrytavern/object-parser'constschema=parser.schema({name: String,age: [String,Number],role: parser.property({type: String,required: false,default: 'anonymous',validator: (value)=>{if(!['anonymous','user','admin'].includes(value))thrownewError('Role must be "anonymous", "user" or "admin".')returntrue},}),})consttarget={name: 'Dmitry',age: 19}constresult=parser.parse(target,schema)// => {// value: { name: 'Dmitry', age: 19, role: 'anonymous' }// errors: []// }

What's going on here:

  1. Imported parser.
  2. Created the object schema where:
    • name - is required property which can be only String.
    • age - is required property which can be String or Number.
    • role - is not required property, which can be only an "anonymous", "user" or "admin" string. Value by default: "anonymous".
  3. Parsed the target object by the object schema.

The result of parsing is an object, where:

  • value - parsed object. By default is a reference on the original object.
  • errors - array of errors. Сontains parsing errors.

Installation

ObjectParser is available via npm:

npm install --save @dmitrytavern/object-parser

Browser/CDN:

<scriptsrc="https://unpkg.com/@dmitrytavern/object-parser/dist/object-parser.min.js"></script>

Usage

CommonJS:

constparser=require('@dmitrytavern/object-parser')const{ parser }=require('@dmitrytavern/object-parser')const{ parse, schema, property }=require('@dmitrytavern/object-parser')

ES6:

importparserfrom'@dmitrytavern/object-parser'import{parser}from'@dmitrytavern/object-parser'import{parse,schema,property}from'@dmitrytavern/object-parser'

Browser:

<script>constparser=window.objectParserconst{ parser }=window.objectParserconst{ parse, schema, property }=window.objectParser</script>

You can use the style you prefer. For more information, see docs.

Documentation

Powerful documentation can be found at dmitrytavern.github.io/object-parser.

License

MIT - check repo files

Copyright (c) 2022-present, Dmitry Tavern

About

A simple and easy way to check and parse an javascript object without pain and with vue-like props schemas. With type checker, exists checker, default setter and custom validator.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages