- Notifications
You must be signed in to change notification settings - Fork1
json-decoder allows TypeScript and JavaScript projects to adorn class declarations with JSON decoding decorators to support automatic decoding and marshalling of JSON objects to full prototype objects.
License
happycodelucky/json-decoder-node
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
json-decoder
allows TypeScript and JavaScript projects to adorn class declarations with JSON decoding decorators to support automatic decoding and marshalling of JSON objects to full prototype objects.
- Installation
- Reflect Metadata
- Simple Decoding
- Property Aliases
- Type Marshalling
- Custom Constructors
- JSON Schema Validation
Of course it can, and the CommonJS module loader of Node.js even makes it easy to userequire('file.json')
so even loading JSON is easy!
With ES6, JavaScript introduced classes. And TypeScript uses classes way more as a first class citizen. Well in JavaScript it's simply to adopt a class prototype, and in TypeScript interfaces give JSON types.
It seems like there's isn't too much utility injson-decoder
? These existing mechanisms are just fine if they work for you, but there are limitations of JSON:
- You get everything, not just what you want (all those extra properties)
- JSON properties might not be named appropriately or desired for your class needs
- JSON properties are limited in types, no support for
Map
,Set
,URL
,Dates
or custom types - JSON property values might need coercing, where there is a
String
, maybe aNumber
, or an object needs to be a custom object - You may need a single property value pulled up from a sub-object property, or a single element of an array.
- Custom translation functions called to covert values
- And more...
To install the module use eitheryarn
ornpm
$ yarn add https://github.com/happycodelucky/json-decoder-node.git
$ npm install -S https://github.com/happycodelucky/json-decoder-node.git
Reflect metadata additions are not yet formally part of EcmaScript so are not available in JavaScript or Node.js.reflect-metadata
is a package that must only be installed once per project. As such, it's is included here as a peer dependency.
To install in any project, use:
$ yarn add reflect-metadata
To install in any model, use:
$ yarn add --peer reflect-metadata
Simplest of all declarations is to declare a class as JSON decodable by using the@jsonDecoable
class decorator. This is required to declare decoding support.
Prototype properties can be decorated with@jsonProperty
, inheriting the prototype property name as the name of the JSON property to map the value to.
import{jsonDecodable,jsonProperty}from'./json-decoder'// Decodable Account class@jsonDecodable()classAccount{// Mapped 'id' property @jsonPropertypublicreadonlyid:number// Mapped 'name' property @jsonPropertypublicreadonlyname:string}
To decode anAccount
class, useJsonDecoder.decode
with a JSON object (or JSON string) and the decodable class to decode, in this caseAccount
import{JsonDecoder}from'json-decoder'import{Account}from'./account'constjson={id:1001,name:'John Smith',}// Decode the above JSON for 'Account' classconstaccount=JsonDecoder.decode<Account>(json,Account)
The class you are authoring and the JSON used as a source might not be a one to one match. You class may want to use different property names or even structure the representation different to the source JSON.
This is where "aliases" come in and thejsonPropertyAlias
comes into play.
The following uses the decorator describing the JSON propertyaccountId
mapped to the class prototype propertyid
.
import{jsonDecodable,jsonPropertyAlias}from'./json-decoder'@jsonDecodable()classAccount{// Alias 'id' to 'accountId' property @jsonPropertyAlias('account-id')publicreadonlyid:number// ...}
Note the JSON object below is usingaccount-id
instead ofid
import{JsonDecoder}from'json-decoder'import{Account}from'./account'constjson={'account-id':1001,name:'John Smith',}constaccount=JsonDecoder.decode<Account>(json,Account)
The decoder will automatically map theid
value based on the alias given in the@jsonPropertyAlias
.
Simple property renaming does not help with restructuring the original JSON. The decoder can help here too withKey Paths alias. Key paths are dot/@-notion paths to JSON values.
If the desire was to flatten a JSON object's properties this can be achieved by using a path similar to that used in TypeScript/JavaScript itself
{id:1001,name:{title:'Dr',fullName:'John Smith',suffix:'III',}}
The of interestname
properties can be flatten
import{jsonDecodable,jsonPropertyAlias}from'./json-decoder'@jsonDecodable()classAccount{ @jsonPropertyAlias('name.title')publicreadonlytitle:string @jsonPropertyAlias('name.fullName')publicreadonlyfullName:string// ...}
The@
-notation can be used to address indexes of arrays if needed.
{id:1001,name:{title:'Dr',fullName:'John Smith',suffix:'III',},profiles:[2001,2002,2451],}
The decode could map index0
ofprofiles
by usingprofiles@0
. At the same time map all the profiles from the JSON.
import{jsonDecodable,jsonPropertyAlias,jsonProperty}from'./json-decoder'@jsonDecodable()classAccount{// ... @jsonPropertyAlias('profiles@0')publicreadonlyprimaryProfile:number @jsonPropertypublicreadonlyprofiles:Array<number>// ...}
Key paths can be a long as the JSON supports.property.arr@0.anotherProperty.YAP
will attempt to look upYAP
, the end value. If at any point any sub-property returnsundefined
thenundefined
will be returned. Ifnull
is returned for any but the last property thenundefined
will be returned, elsenull
will be returned.
@
and.
are synonymous with one another (subject to change) but provide a more readable structure of intent. That is '.' sub-property, '@' index.a.b.c
is the same asa@b@c
.
As a convenience, you may use@index
as an alias, which will attempt to map a source JSON object that is an array, atindex
to the class prototype property.
Using an example of a message protocol from a network request, the message is composed of a[header, body]
structure.
[{message:'ACCOUNT'},{name:'John Smith'},]
Decoding the above message use@jsonPropertyAlias('@1.name')
, where@1
represents the body of the message.
import{jsonDecodable,jsonPropertyAlias}from'./json-decoder'@jsonDecodable()classAccountMessage{// ... @jsonPropertyAlias('@1.name')publicreadonlyname:string// ...}
Type marshalling is a built-in feature of the decoder. Type marshalling allows a property of one type to be automatically converted into another. This allows more flexibility and implicit type conversion to happen automatically.
The@jsonType
decorator allows the declaration of the class to marshal the property value to. Natively supported types are:
- Array
- Boolean
- Date (as timestamp or string)
- Map
- Number
- Set
- URL
If class passed to@jsonType()
isalso a@jsonDecodable
class, thenjson-decoder
will attempt to deserialize the object associated with the current@jsonProperty
using the specified class.
import{jsonDecodable,jsonType}from'./json-decoder'@jsonDecodable()classAccount{// Use 'Number' marshalling @jsonProperty @jsonType(Number)publicreadonlyid:number}
The above will attempt to convert a JSON property value ofid
into aNumber
. The marshalling attempts to perform a smart conversion based on the property in the JSON. ForNumber
s this could be Integers or Floats, and supports Base10, Base16 (Hex) and Base2 (Binary) number strings similar to JavaScript notation.
import{JsonDecoder}from'json-decoder'import{Account}from'./account'constjson={id:'0x3E9',name:'John Smith',}constaccount=JsonDecoder.decode<Account>(json,Account)
jsonType
can also be used to marshal iterable collections such asArray
,Map
andSet
. To specify a collection with a specific type of element,@jsonType({ collection: Array | Map | Set, element: Type })
(an array of one type element).
{id:1001,profiles:['2001','2002','2451'],}
To marshalprofiles
into anArray
ofNumber
import{jsonDecodable,jsonType}from'./json-decoder'@jsonDecodable()classAccount{// ... @jsonType({collection:Array,element:Number})publicreadonlyprofiles:Array<number>// ...}
element
types can also be nested collections. For example:
import{jsonDecodable,jsonType}from'./json-decoder'@jsonDecodable()classAccount{// ... @jsonType({collection:Map,element:{collection:Map,element:String}})publicreadonlynestedMap:Map<string,Map<string,string>>// ...}
Array marshalling can also convert a single property value into an array. If the JSON object only had a single scalar property value instead, it will creating anArray
of one element.
All element marshaling still apply here too
{id:1001,profiles:'2001',}
With marshaling arrays, a JSON property with an array can be marshalled into a single property value. In this case only the first element of the array is taken.
{id:1001,profiles:['2001','2002','2451'],}
// Marshal `profiles` into a single value @jsonType(Number)publicreadonly primaryProfile:number// ... @jsonType({collection:Array,element:Number})publicreadonlyprofiles:Array<number>
When decodedprimaryProfile
will be set to2001
as aNumber
Sometimes when marshaling a given attribute, one may wish to apply custom business logic to calculate the value that is assigned to the@jsonProperty
. To accomplish this, a function may be optionally passed as a second parameter to@jsonType
with a signature of:
(value:Type):OtherType
For example, if a source JSON document contains an unbounded numeric value but once deserialized, it should be limited to a maximum decimal value:
{id:1001,size:9999,}
constMAX_VALUE=1000.01 @jsonType(Number)publicreadonly id:number @jsonPropertyAlias('size') @jsonType(Number,(data:number):number=>{returnMath.min(MAX_VALUE,data)})publicreadonly decimalSize:Number
Sometimes when instantiating a@jsonDecodable
class, it becomes necessary to execute some custom initialization code in the class constructor. However,json-decoder
willnot use the constructor unless directed to do so. To cause the class constructor to get invoked whendecode()
is called, pass{ useConstructor: true }
to@jsonDecodable
.
import{jsonDecodable,jsonType}from'./json-decoder'@jsonDecodable({useConstructor:true})classAccount{constructor(){super()// do custom initialization} @jsonProperty @jsonType(Number)publicreadonlyid:number}
Similarly, if one is using inheritance to describe@jsonDecodable
classes, it may be desirable to calldecode
on a base class (which may beabstract
), and dynamically instantiate a derived class based on the contents of the JSON.
@jsonDecodable({useConstructor:true})abstractclassBaseClass{ @jsonPropertyname:string @jsonPropertyid:number @jsonDecoderFactorystaticdecoderClassFactory(json:JsonObject):DerivedClass_1|DerivedClass_2{returnjson['some-attribute']==='some value' ?newDerivedClass_1() :newDerivedClass_2()}abstracttoJSON():JsonObject}
json-decoder
supports validation of JSON documents usingJSON Schema. To enable schema validation, add the@jsonSchema()
decorator to your class definition.
import{jsonDecodable,jsonType}from'./json-decoder'interfaceMyData{foo:numberbar?:string}constschema:JSONSchemaType<MyData>={$id:"http://schemas.example.com/my-data",$schema:"http://json-schema.org/draft-07/schema#",description:"This is my data.",type:"object",properties:{foo:{type:"integer"},bar:{type:"string",nullable:true}},required:["foo"],additionalProperties:false}@jsonDecodable({useConstructor:true})@jsonSchema(schema)classAccount{// Use 'Number' marshalling @jsonPropertypublicreadonlyfoo:number @jsonPropertybar?:string}
Whendecode()
is called, the schema validation will be executed automatically. If validation fails for any reason anError
will be thrown containing each of the validation errors encountered.
About
json-decoder allows TypeScript and JavaScript projects to adorn class declarations with JSON decoding decorators to support automatic decoding and marshalling of JSON objects to full prototype objects.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.