jsonbase
Check and transform your JSON data.
Why jsonbase?
jsonbase is mainly built for back-to-front-end data communication. Sometimes we may have the issue that data from the server is not in the right type for JavaScript and some weird problem may happen, like the following example:
This is the JSON data return by server:
and this is the JSON data we expected:
So here's the problem: the friends
field should be a number
, not a string
. And if we add 1 to it, we will only get '181'
other than 19
. This has the similar problem with address
and confirmed
field.
With jsonbase, we can prevent the tragedy by checking and converting data types:
var DataTypes = jsonbaseDataTypes;var schema = name: DataTypesstring friends: DataTypesnumber address: DataTypesstring confirmed: DataTypebool;jsonbase;/* * { * "name": "Peter", * "friends": 18, * "address": "", * "confirmed": true * } */
Usage
Installation
-
Node:
npm install jsonbase
-
Other:
- Just clone the repo and use
index.js
- jsonbase supports AMD & CMD module systems.
- Just clone the repo and use
Basic jsonbase data types:
Please see
test/jsonbase.test.js
for details.
- DataTypes.nul: mark a field as a null,
null
,0
,''
=>null
,- or a
TypeNotMatchError
will be thrown.
- DataTypes.bool: mark a field as a boolean,
null
,false
,0
,'false'
=>false
,true
,1
,'true'
=>true
,- or a
TypeNotMatchError
will be thrown.
- DataTypes.number: mark a field as a number,
null
=>0
,true
andfalse
=>1
and0
,- numbers will remain what they are,
- and strings consist of pure numbers will converted to the corresponding numbers.
- You will get a
TypeNotMatchError
from other data types.
- DataTypes.string: mark a field as a string,
null
=>''
,true
=>'true'
,false
=>'false'
,- strings remains what they are,
- You will get a
TypeNotMatchError
from other data types.
- DataTypes.array: mark a field as an array:
- arrays remains what they are,
- or a
TypeNotMatchError
will be thrown.
- DataTypes.array: mark a field as an object:
- objects remains what they are,
- or a
TypeNotMatchError
will be thrown.
Schema
jsonbase uses schema to validate and convert JSON object. jsonbase supports nested schema so you can use it on complex JSON data:
var DataTypes = jsonbaseDataTypes;var parsedJSON = "name": "jsonbase" "stargazers_count": 0 "owner": "id": 1234567890 "site_admin": false "a_made_up_field": "id": 1 "arr": false 1 null "id": 2 "arr": true 2 null ;var schema = name: DataTypesstring stargazers_count: DataTypesnumber owner: id: DataTypesnumber site_admin: DataTypesbool a_made_up_field: id: DataTypesnumber arr: DataTypesarray ;jsonbase;