The JSON format natively doesn't support binary data. The binary data has to be escaped so that it can be placed into a string element (i.e. zero or more Unicode chars in double quotes using backslash escapes) in JSON.

转义二进制数据的一个明显方法是使用base64.但是,Base64的处理开销很高.此外,它将3个字节扩展为4个字符,这导致数据大小增加了约33%.

One use case for this is the v0.8 draft of the CDMI cloud storage API specification. You create data objects via a REST-Webservice using JSON, e.g.

PUT /MyContainer/BinaryObject HTTP/1.1
Host: cloud.example.com
Accept: application/vnd.org.snia.cdmi.dataobject+json
Content-Type: application/vnd.org.snia.cdmi.dataobject+json
X-CDMI-Specification-Version: 1.0
{
    "mimetype" : "application/octet-stream",
    "metadata" : [ ],
    "value" :   "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
    IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
    dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
    dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
    ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=",
}

有没有更好的方法和标准方法将二进制数据编码成JSON字符串?

推荐答案

根据JSON规范,有94个Unicode字符可以表示为一个字节(如果您的JSON是以UTF-8传输的).考虑到这一点,我认为在空格方面最好是base85,它将四个字节表示为五个字符.然而,与base64相比,这只提高了7%,计算成本更高,而且实现不如base64常见,所以这可能不是一个胜利.

You could also simply map every input byte to the corresponding character in U+0000-U+00FF, then do the minimum encoding required by the JSON standard to pass those characters; the advantage here is that the required decoding is nil beyond builtin functions, but the space efficiency is bad -- a 105% expansion (if all input bytes are equally likely) vs. 25% for base85 or 33% for base64.

最终裁决:在我看来,base64获胜的理由是,enough分球很普通、很容易,而且还不错,可以换人.

另见:Base91Base122

Json相关问答推荐

使用Shell深入挖掘到最低的SON元素

JOLT拉平数组

将json数组反序列化为选项 struct

Swift解码错误类型与`Bool`type不一致

替换字符串中特殊字符的Jolt变换

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

阅读 JSON 正文 Firebase 云函数

Serde JSON 反序列化枚举

如何在 Dart 中与多个 map (字典)相交

在 rust 中从 API 反序列化 serde_json

一起使用 Argparse 和 Json

python,将Json写入文件

十六进制格式可以与 JSON 文件一起使用吗?如果是这样,怎么做?

Android JSON 库的性能和可用性比较

Jackson 没有使用 @JsonProperty 覆盖 Getter

使用绝对或相对路径在 curl 请求中发送 json 文件

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

是否可以将数据写入本地 json 文件,除了Angular 之外什么都没有?

JSON.parse 返回字符串而不是对象

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)