Skip to content

EJSON

EJSON 是 JSON 的扩展,以支持更多类型。它支持所有 JSON 安全类型,以及:

¥EJSON is an extension of JSON to support more types. It supports all JSON-safe types, as well as:

  • 日期 (JavaScript Date)

    ¥Date (JavaScript Date)

  • 二进制(JavaScript Uint8ArrayEJSON.newBinary 的结果)

    ¥Binary (JavaScript Uint8Array or the result of EJSON.newBinary)

  • 特殊数字(JavaScript NaNInfinity-Infinity

    ¥Special numbers (JavaScript NaN, Infinity, and -Infinity)

  • 正则表达式 (JavaScript RegExp)

    ¥Regular expressions (JavaScript RegExp)

  • 用户定义的类型(参见 EJSON.addType。例如,Mongo.ObjectID 就是以这种方式实现的。)

    ¥User-defined types (see EJSON.addType. For example, Mongo.ObjectID is implemented this way.)

所有 EJSON 序列化也是有效的 JSON。例如,具有日期和二进制缓冲区的对象将在 EJSON 中序列化为:

¥All EJSON serializations are also valid JSON. For example an object with a date and a binary buffer would be serialized in EJSON as:

json
{
  "d": { "$date": 1358205756553 },
  "b": { "$binary": "c3VyZS4=" }
}

Meteor 支持发布者、方法参数和结果、Mongo 数据库和 Session 变量中的所有内置 EJSON 数据类型。

¥Meteor supports all built-in EJSON data types in publishers, method arguments and results, Mongo databases, and Session variables.

EJSON.parse

Summary:

Parse a string into an EJSON value. Throws an error if the string is not valid EJSON.

Arguments:

Source code
NameTypeDescriptionRequired
strString

A string to parse into an EJSON value.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.parse();
  "str"
);

EJSON.stringify

Summary:

Serialize a value to a string. For EJSON values, the serialization fully represents the value. For non-EJSON values, serializes the same way as JSON.stringify.

Arguments:

Source code
NameTypeDescriptionRequired
valEJSON

A value to stringify.

Yes
optionsObjectNo
options.indentBoolean, Integer or String

Indents objects and arrays for easy readability. When true, indents by 2 spaces; when an integer, indents by that number of spaces; and when a string, uses the string as the indentation pattern.

No
options.canonicalBoolean

When true, stringifies keys in an object in sorted order.

No
js
import { EJSON } from "meteor/ejson";

EJSON.stringify(
  { num: 42, someProp: "foo" },
  options // this param is optional
);

EJSON.fromJSONValue

Summary:

Deserialize an EJSON value from its plain JSON representation.

Arguments:

Source code
NameTypeDescriptionRequired
valJSONCompatible

A value to deserialize into EJSON.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.fromJSONValue();
 { num:  42 , someProp:  "foo" }
);

EJSON.toJSONValue

Summary:

Serialize an EJSON-compatible value into its plain JSON representation.

Arguments:

Source code
NameTypeDescriptionRequired
valEJSON

A value to serialize to plain JSON.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.toJSONValue();
 { num:  42 , someProp:  "foo" }
);

EJSON.equals

Summary:

Return true if a and b are equal to each other. Return false otherwise. Uses the equals method on a if present, otherwise performs a deep comparison.

Arguments:

Source code
NameTypeDescriptionRequired
aEJSON----Yes
bEJSON----Yes
optionsObjectNo

Options:

NameTypeDescriptionRequired
keyOrderSensitiveBoolean

Compare in key sensitive order, if supported by the JavaScript implementation. For example, {a: 1, b: 2} is equal to {b: 2, a: 1} only when keyOrderSensitive is false. The default is false.

No
js
import { EJSON } from "meteor/ejson";


const result = EJSON.equals();
 { num:  42 , someProp:  "foo" },
{ num: 42 , someProp: "foo" },

options, // this param is optional
);

EJSON.clone

Summary:

Return a deep copy of val.

Arguments:

Source code
NameTypeDescriptionRequired
valEJSON

A value to copy.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.clone();
 { num:  42 , someProp:  "foo" }
);

EJSON.newBinary

Summary:

Allocate a new buffer of binary data that EJSON can serialize.

Arguments:

Source code
NameTypeDescriptionRequired
sizeNumber

The number of bytes of binary data to allocate.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.newBinary();
  42
);

二进制数据缓冲区由支持它们的 JavaScript 平台上的 Uint8Array 实例表示。在不支持 Uint8Array 的 JavaScript 实现中,二进制数据缓冲区由包含从 0 到 255 的数字的标准数组表示,并且 $Uint8ArrayPolyfill 键设置为 true

¥Buffers of binary data are represented by Uint8Array instances on JavaScript platforms that support them. On implementations of JavaScript that do not support Uint8Array, binary data buffers are represented by standard arrays containing numbers ranging from 0 to 255, and the $Uint8ArrayPolyfill key set to true.

EJSON.isBinary

Summary:

Returns true if x is a buffer of binary data, as returned from EJSON.newBinary.

Arguments:

Source code
NameTypeDescriptionRequired
xObject

The variable to check.

Yes
js
import { EJSON } from "meteor/ejson";


const result = EJSON.isBinary();
  x
);

EJSON.addType

Summary:

Add a custom datatype to EJSON.

Arguments:

Source code
NameTypeDescriptionRequired
nameString

A tag for your custom type; must be unique among custom data types defined in your project, and must match the result of your type's typeName method.

Yes
factoryfunction

A function that deserializes a JSON-compatible value into an instance of your type. This should match the serialization performed by your type's toJSONValue method.

Yes

传递给 EJSON.addType 方法的工厂函数应创建我们自定义类型的实例,并使用作为工厂函数的第一个参数传递的对象中的值对其进行初始化。这是一个例子:

¥The factory function passed to the EJSON.addType method should create an instance of our custom type and initialize it with values from an object passed as the first argument of the factory function. Here is an example:

js
class Distance {
  constructor(value, unit) {
    this.value = value;
    this.unit = unit;
  }

  // Convert our type to JSON.
  toJSONValue() {
    return {
      value: this.value,
      unit: this.unit,
    };
  }

  // Unique type name.
  typeName() {
    return "Distance";
  }
}

EJSON.addType("Distance", function fromJSONValue(json) {
  return new Distance(json.value, json.unit);
});

EJSON.stringify(new Distance(10, "m"));
// Returns '{"$type":"Distance","$value":{"value":10,"unit":"m"}}'

将类型添加到 EJSON 时,Meteor 将能够在以下位置使用该类型:

¥When you add a type to EJSON, Meteor will be able to use that type in:

  • 如果你将你类型的对象传递给发布处理程序,则发布它们。

    ¥publishing objects of your type if you pass them to publish handlers.

  • 允许你在 methods 的返回值或参数中输入类型。

    ¥allowing your type in the return values or arguments to methods.

  • 在 Minimongo 中将你的类型存储在客户端。

    ¥storing your type client-side in Minimongo.

  • 允许你在 Session 变量中输入类型。

    ¥allowing your type in Session variables.

你的类型的实例必须实现 typeNametoJSONValue 方法,如果默认实现不够,则可以实现 cloneequals 方法。

¥Instances of your type must implement typeName and toJSONValue methods, and may implement clone and equals methods if the default implementations are not sufficient.

CustomType.typeName

Summary:

Return the tag used to identify this type. This must match the tag used to register this type with EJSON.addType.

CustomType.toJSONValue

Summary:

Serialize this instance into a JSON-compatible value.

例如,Mongo.ObjectIDtoJSONValue 方法可以是:

¥For example, the toJSONValue method for Mongo.ObjectID could be:

js
function () {
  return this.toHexString();
}

CustomType.clone

Summary:

Return a value r such that this.equals(r) is true, and modifications to r do not affect this and vice versa.

如果你的类型没有 clone 方法,EJSON.clone 将改用 toJSONValue 和工厂。

¥If your type does not have a clone method, EJSON.clone will use toJSONValue and the factory instead.

CustomType.equals

Summary:

Return true if other has a value equal to this; false otherwise.

Arguments:

Source code
NameTypeDescriptionRequired
otherObject

Another object to compare this to.

Yes

equals 方法应该定义一个 等价关系。它应该具有以下属性:

¥The equals method should define an equivalence relation. It should have the following properties:

  • 反身性 - 对于任何实例 aa.equals(a) 必须为真。

    ¥Reflexivity - for any instance a: a.equals(a) must be true.

  • 对称性 - 对于任何两个实例 ab:当且仅当 b.equals(a) 存在时,为 a.equals(b)

    ¥Symmetry - for any two instances a and b: a.equals(b) if and only if b.equals(a).

  • 传递性 - 对于任何三个实例 abca.equals(b)b.equals(c) 意味着 a.equals(c)

    ¥Transitivity - for any three instances a, b, and c: a.equals(b) and b.equals(c) implies a.equals(c).

如果你的类型没有 equals 方法,EJSON.equals 将改用调用 toJSONValue 的结果进行比较。

¥If your type does not have an equals method, EJSON.equals will compare the result of calling toJSONValue instead.