JSON已得到广泛应用,在很多应用场景下,你可能想进一步地压缩JSON字符串的长度,以提升传输效率,这里向你介绍两种常用的同构压缩算法:CJSON和HPack。
[
{ // This is a point
"x": 100,
"y": 100
}, { // This is a rectangle
"x": 100,
"y": 100,
"width": 200,
"height": 150
},
{}, // an empty object
]
CJSON压缩后:
{
"templates": [
[0, "x", "y"], [1, "width", "height"]
],
"values": [
{ "values": [ 1, 100, 100 ] },
{ "values": [2, 100, 100, 200, 150 ] },
{}
]
}
[{
name : "Andrea",
age : 31,
gender : "Male",
skilled : true
}, {
name : "Eva",
age : 27,
gender : "Female",
skilled : true
}, {
name : "Daniele",
age : 26,
gender : "Male",
skilled : false
}]
[["name","age","gender","skilled"],["Andrea",31,"Male",true],["Eva",27,"Female",true],["Daniele",26,"Male",false]]
我目前正在使用的是基于HPACK算法的开源项目JSONP:https://github.com/WebReflection/JSONH,数据量越大,效果越明显,应用场景也更加有意义。
参考:http://web-resource-optimization.blogspot.com/2011/06/json-compression-algorithms.html