canonical-json

2019-02-14 admin

canonical-json是什么

什么是canonical-json,a canonical json implementation

canonical-json使用教程帮助文档

Canonical JSON

The goal of this module is to implement a version of JSON.stringify that returns a canonical JSON format.

Canonical JSON means that the same object should always be stringified to the exact same string. JavaScripts native JSON.stringify does not guarantee any order for object keys when serializing:

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

Source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

This module implements two alternative solutions to this problem:

  • index.js is based on Douglas Crockford’s json2.js. I modified it to serialize object keys sorted on the fly.
  • index2.js recursively creates a copy of the object to sort its keys. The copy is then simply passed to native JSON.stringify

It currently exports the index.js version.

Performance comparison

I compared the performance of native JSON.stringify and the two alternative implementations that output keys sorted:

  • native JSON.stringify: 75 ms
  • js JSON.stringify with sorted keys (implementation): 308 ms
  • copy and native JSON.stringify with sorted keys (implementation): 291 ms

The tests were run in Node.js on a 2011 MacBook Pro. Performance test source: test/performance.js

Command Line Interface

To run this from the command line you can use canonical-json.js like so:

cat sample.json | ./canonical-json.js > sample-canonical.json

Links

  • CANON is a project with similar goals.

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-53723.html

文章标题:canonical-json

回到顶部