All Projects → rse → Ducky

rse / Ducky

Duck-Typed Value Handling for JavaScript

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Ducky

Dataclass factory
Modern way to convert python dataclasses or other objects to and from more common types like dicts or json-like structures
Stars: ✭ 116 (+63.38%)
Mutual labels:  json, typing
Gojsonq
A simple Go package to Query over JSON/YAML/XML/CSV Data
Stars: ✭ 1,790 (+2421.13%)
Mutual labels:  json, query
Autocomplete
🔮 Fast and full-featured autocomplete library
Stars: ✭ 1,268 (+1685.92%)
Mutual labels:  query, select
Octosql
OctoSQL is a query tool that allows you to join, analyse and transform data from multiple databases and file formats using SQL.
Stars: ✭ 2,579 (+3532.39%)
Mutual labels:  json, query
Jslt
JSON query and transformation language
Stars: ✭ 367 (+416.9%)
Mutual labels:  json, query
Rumble
⛈️ Rumble 1.11.0 "Banyan Tree"🌳 for Apache Spark | Run queries on your large-scale, messy JSON-like data (JSON, text, CSV, Parquet, ROOT, AVRO, SVM...) | No install required (just a jar to download) | Declarative Machine Learning and more
Stars: ✭ 58 (-18.31%)
Mutual labels:  json, query
Typedload
Python library to load dynamically typed data into statically typed data structures
Stars: ✭ 120 (+69.01%)
Mutual labels:  json, typing
aarbac
An Automated Role Based Access Control .NET framework with T-SQL Query Parser which automatically parse select, insert, update, delete queries based on the logged in user role
Stars: ✭ 18 (-74.65%)
Mutual labels:  query, select
node-reactive-postgres
Reactive queries for PostgreSQL
Stars: ✭ 28 (-60.56%)
Mutual labels:  query, select
Dasel
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Stars: ✭ 759 (+969.01%)
Mutual labels:  json, query
Js Jsonq
A simple Javascript Library to Query over Json Data
Stars: ✭ 67 (-5.63%)
Mutual labels:  json, query
Elm Json Tree View
A library for Elm that shows JSON data as an expandable HTML tree
Stars: ✭ 70 (-1.41%)
Mutual labels:  json
Servicestack.text
.NET's fastest JSON, JSV and CSV Text Serializers
Stars: ✭ 1,157 (+1529.58%)
Mutual labels:  json
Magento2 Import Export Sample Files
Default Magento 2 CE import / export CSV files & sample files for Firebear Improved Import / Export extension
Stars: ✭ 68 (-4.23%)
Mutual labels:  json
Httpz
purely functional http client with scalaz.Free
Stars: ✭ 67 (-5.63%)
Mutual labels:  json
Fipe Json
🚘 FIPE API - Listagem com preço médio de veículos: carro, moto e caminhão.
Stars: ✭ 71 (+0%)
Mutual labels:  json
Avocado
Strongly-typed MongoDB driver for Rust
Stars: ✭ 70 (-1.41%)
Mutual labels:  json
Null
reasonable handling of nullable values
Stars: ✭ 1,148 (+1516.9%)
Mutual labels:  json
Randomjson
Provides a Kotlin/Java library to create a random json string
Stars: ✭ 70 (-1.41%)
Mutual labels:  json
Cti Taxii Client
OASIS TC Open Repository: TAXII 2 Client Library Written in Python
Stars: ✭ 67 (-5.63%)
Mutual labels:  json

Ducky — duckyjs.com

Duck-Typed Value Handling for JavaScript

Abstract

Ducky is a small Open-Source JavaScript library, providing Duck-Typed Value Validation, Value Selection and Flexible Function Parameter Handling. It can be used in Node.js based server and browser based client environments.

Getting Ducky

You can conveniently get Ducky in various ways:

  • NPM: install as server component via the Node Package Manager:
    $ npm install ducky

  • Git: directly clone the official repository:
    $ git clone https://github.com/rse/ducky.git

  • cURL: download only the main file from the repository:
    $ curl -O https://raw.github.com/rse/ducky/master/lib/ducky.browser.js

API

Ducky provides the following API:

ducky.version = { major: Number, minor: Number, micro: Number, date: Number }

The version of Ducky, provided as a tuple of separate pieces, for easy comparison.

if (!(ducky.version.major >= 2 && ducky.version.minor >= 0))
    throw new Error("need at least Ducky 2.0.0");

ducky.register(name: String, type: Function): void

Register under name an additional host or application type, represented by the constructor function type. This allows ducky.validate() and ducky.params() to validate objects which are instances of the type.

var Foo = function () { ... };
ducky.register("app.Foo", Foo);
ducky.validate(new Foo(), "app.Foo");

The following host types are pre-registered by default (if actually existing in the particular native or "polyfilled" host environment): Object, Boolean, Number, String, Function, RegExp, Array, Date, Error, Set, Map, WeakMap, Promise, Proxy and Iterator.

ducky.unregister(name: String): void

Unregisters the additional host or application type, which was previously registered under name with ducky.register().

ducky.unregister("app.Foo");

ducky.select(object: Object, path: String, value?: Object): Object

Dereference into (and this way subset) object according to the path specification and either return the dereferenced value or set a new value. Object has to be a hash or array object. The path argument has to follow the following grammar (which is a direct JavaScript dereferencing syntax):

LHS RHS
path ::= segment segment*
segment ::= bybareword | bykey
bybareword ::= "."? identifier
bykey ::= "[" key "]"
identifier ::= /[_a-zA-Z$][_a-zA-Z$0-9]*>/
key ::= number | squote | dquote
number ::= /[0-9]+/
dquote ::= `/"(?:\"
squote ::= `/'(?:\'

Setting the value to undefined effectively removes the dereferenced value. If the dereferenced parent object is a hash, this means the value is delete'ed from it. If the dereferenced parent object is an array, this means the value is splice'ed out of it.

ducky.select({ foo: { bar: { baz: [ 42, 7, "Quux" ] } } },
    "foo['bar'].baz[2]") // → "Quux"

In case caching of the internally compiled Abstract Syntax Tree (AST) is not wishes, you can perform the compile and execute steps of ducky.select individually:

ducky.select.compile(path: String): Object

Compile the selection specification path into an AST.

ducky.select.execute(object: Object, ast: Object, value?: Object): Object

Select from object a value via ast and either return it or set it to the new value value.

ducky.validate(object: Object, spec: String, errors?: String[]): Boolean

Validate an arbitrary nested JavaScript object object against the specification spec. The specification spec has to be a string following the following grammar (which is a mixture of JSON-like structure and RegExp-like quantifiers):

LHS RHS
spec ::= not | alt | hash | array | any | regexp | primary | class
not ::= "!" spec
alt ::= "(" spec ("|" spec)* ")"
hash ::= "{" (key arity? ":" spec ("," key arity? ":" spec)*)? "}"
array ::= "[" (spec arity? ("," spec arity?)*)? "]"
arity ::= "?" | "*" | "+" | "{" number "," (number | "oo") "}"
number ::= /^[0-9]+$/
key ::= /^[_a-zA-Z$][_a-zA-Z$0-9]*$/ | "@"
any ::= "any"
regexp ::= `/^/(?:\/
primary ::= `/^(?:null
class ::= /^[_a-zA-Z$][_a-zA-Z$0-9]\*(?:\.[_a-zA-Z$][_a-zA-Z$0-9]\*)\*$/

The special key @ can be used to match an arbitrary hash element key.

ducky.validate({ foo: "Foo", bar: "Bar", baz: [ 42, 7, "Quux" ] },
    "{ foo: string, bar: any, baz: [ number+, string* ], quux?: any }") // &arr; true

If an empty errors array is given, use it to assemble detailed error messages in case of a validation failure.

In case caching of the internally compiled Abstract Syntax Tree (AST) is not wishes, you can perform the compile and execute steps of ducky.validate individually:

ducky.validate.compile(spec: String): Object

Compile the validation specification spec into an AST.

ducky.validate.execute(object: Object, ast: Object, errors?: String[]): Boolean

Validate object against ast and return true in case it validates. If an empty errors array is given, use it to assemble detailed error messages in case of a validation failure.

ducky.params(name: String, args: Object[], spec: Object): Object

Handle positional and named function parameters by processing a function's arguments array. Parameter name is the name of the function for use in exceptions in case of invalid parameters. Parameter args usually is the JavaScript arguments pseudo-array of a function. Parameter spec is the parameter specification: each key is the name of a parameter and the value has to be an Object with the following possible fields: pos for the optional position in case of positional usage, def for the default value (of not required and hence optional parameters), req to indicate whether the parameter is required and valid for type validation (a validation specification string accepted by the validate>() method).

function config () {
    var params = ducky.params("config", arguments, {
        scope: { pos: 0, req: true,      valid: "boolean"           },
        key:   { pos: 1, req: true,      valid: /^[a-z][a-z0-9_]*$/ },
        value: { pos: 2, def: undefined, valid: "object"            },
        force: {         def: false,     valid: "boolean"           }
    });
    var result = cfg_get(params.scope, params.key);
    if (typeof params.value !== "undefined")
        cfg_set(params.scope, params.key, params.value, params.force);
    return result;
}
var value = config("foo", "bar");
config("foo", "bar", "quux");
config({ scope: "foo", key: "bar", value: "quux", force: true });

ducky.options(spec: Object, options?: Object): Object

Manage configuration option objects. Parameter spec is the option object specification: each key is the name of a parameter (or a sub-path) and the value has to be an Array with a type specification accepted by the validate() method as its first element and optionally a default value as the second element. If no default value is given for an option, it has to exist on initial value merging. Value merging is performed either when the options parameter is given or method merge(options: Object): Object is called on the resulting option object.

function config (options) {
    var options = ducky.options({
        foo:      [ "string"           ],
        bar:      [ "boolean", false   ],
        quux:     [ "number",  1.2     ],
        sub: {
            foo:  [ "string",  "dummy" ],
            bar:  [ "boolean", false   ],
            quux: [ "number",  2.4     ]
        }
    });
    options.merge({ foo: "bar", sub: { bar: true } })
    options.merge({ sub: { quux: 4.8 } })
}

License

Copyright (c) 2010-2021 Dr. Ralf S. Engelschall (http://engelschall.com/)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].