Meteor - EJSON


Advertisements

EJSON is an extension of JSON syntax that supports Date and Binary types.

Install EJSON

To install EJSON package, we need to add it from the command prompt window.

C:\Users\username\Desktop\meteorApp>meteor add ejson

Date Example

We can deserialize the date using the parse method.

if (Meteor.isClient) {
   var myEjsonDate = '{"$date": 1455029631493}';
   var myDate = EJSON.parse(myEjsonDate);
   console.log(myDate);
}

The console will log the correct date value.

Meteor EJSON Date

Binary Example

The same can be applied to binary types.

if (Meteor.isClient) {
   var myEjsonBinary = '{"$binary": "c3VyZS4="}';
   var myBinary = EJSON.parse(myEjsonBinary);
   console.log(myBinary);
}

You can see that the console is logging new deserialized value.

Meteor EJSON Binary

Stringify

We can serialize an object using the stringify method. This is the reversed process from the example above.

if (Meteor.isClient) {

   var myObject = {
      myDate : new Date(),
      myBinary : new Uint8Array([115, 117, 114, 101, 46])
   }

   var myEjosnData = EJSON.stringify(myObject);
   console.log(myEjosnData);
}

We can see our new values in the console.

Meteor EJSON Stringify

Sr.No. Method & Details
1

EJSON.parse(string)

Used for parsing a string into EJSON value.

2

EJSON.stringify(value)

Used for serializing a value to the string.

3

EJSON.fromJSONValue(value)

Used for deserializing an EJSON value from JSON.

4

EJSON.toJSONValue(value)

Used for serializing an EJSON value into JSON.

5

EJSON.equals(value1, value2)

Used for comparing if two values are equal.

6

EJSON.clone(value)

Used for returning a deep copy of the value.

7

EJSON.newBinary

Used for assigning a binary data that EJSON can serialize.

8

EJSON.isBinary(x)

Used for checking if the value is a binary data.

9

EJSON.addType(name, factory)

Used for creating a custom EJSON type.

10

customType.typeName()

Used for returning a name of the custom type.

11

customType.toJSONValue()

Used for serializing custom types.

12

customType.clone()

Used for returning a deep copy of the custom type.

13

customType.equals(otherValue)

Used for comparison between the custom type value and other value.

Advertisements