是否有可用于浏览器的二进制 JSON javascript 库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7541552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:27:52  来源:igfitidea点击:

Is a binary JSON javascript library available for browsers?

javascriptjsonbrowserwebsocketbson

提问by Lorenz Lo Sauer

In order for efficient server side parsing I am looking into a BSON solution directly for the browser javascript environment. The idea is to utilize the entire ASCII space by means of binary websockets. Any suggestions?

为了高效的服务器端解析,我正在研究直接用于浏览器 javascript 环境的 BSON 解决方案。这个想法是通过二进制 websockets 来利用整个 ASCII 空间。有什么建议?

(Any nodejs suggestions are welcome as well)

(也欢迎任何 nodejs 建议)

See also: http://bsonspec.org/

另见:http: //bsonspec.org/

采纳答案by kanaka

This might be incomplete but the goal of the project line up with what you want: https://github.com/muhmi/javascript-bsonIt doesn't look like that encodes directly to typed arrays which would be the most useful for sending over WebSocket.

这可能不完整,但项目的目标与您想要的一致:https: //github.com/muhmi/javascript-bson它看起来不像直接编码到类型化数组,这对发送最有用通过 WebSocket。

回答by jriggins

For what it's worth, it appears that the MongoDB team now have a supported Javascript BSON project:

就其价值而言,MongoDB 团队现在似乎有一个受支持的 Javascript BSON 项目:

https://github.com/mongodb/js-bson

https://github.com/mongodb/js-bson

I'm no expert with the library, but the project claims to work in both Node and the browser. Below is a modified sample from their site:

我不是该库的专家,但该项目声称可以在 Node 和浏览器中运行。以下是来自他们网站的修改后的示例:

<head>
  <!-- Originally https://raw.github.com/mongodb/js-bson/master/browser_build/bson.js -->
  <!-- But downloaded and hosted locally -->
  <script src="./bson.js"></script>
</head>
<body onload="start();">
<script>
  function start() {
    var BSON = bson().BSON;
    var Long = bson().Long;

    var doc = {
      oid: bson().ObjectID(),
      long: Long.fromNumber(100),
      date: new Date(),
      string: "js-bson sample",
      obj: { 
        string: "Object within an object"
      }
    }
    console.log("doc %o", doc);

    // Serialize a document
    var data = BSON.serialize(doc, false, true, false);
    console.log("data %o", data);

    // De serialize it again
    var doc_2 = BSON.deserialize(data);
    console.log("doc_2 %o", doc_2);
  }
</script>
</body>

Below are my results in Chrome:

以下是我在 Chrome 中的结果:

enter image description here

在此处输入图片说明

回答by sogurb

Here in 2019 modern browsers already have embedded the functions:

在 2019 年,现代浏览器已经嵌入了以下功能:

btoa("string to be coded on base64 format") 
atob("base64 string to be uncoded")

As you can see here: https://caniuse.com/#search=btoaAll browsers listed have this feature.

正如您在此处看到的:https: //caniuse.com/#search=btoa列出的所有浏览器都具有此功能。