在nodejs中使用双引号切片缓冲区时获取额外字符

时间:2015-01-20 03:54:03

标签: javascript node.js encoding buffer special-characters

我试图将javascript对象(字符串化)裁剪为确定的大小(特别是Apple推送通知256 Max),但是我刚发现当我的其中一个变量有一个包含双引号的字符串时,它会获得一个额外的字符那个混乱的限制,在下面的例子中我复制它有30个大小限制

var object = {"hola":"mundo", "data":""}

var objectBuffer = new Buffer(JSON.stringify(object))
    console.log(objectBuffer.length) // this should be 26 OK

var data0 = new Buffer('normal', 'utf-8')
console.log(data0.length) // this should be 6 OK

var data1 = new Buffer('"normal', 'utf-8') // Note extra double quote (it only happends with double quotes weird characters like ó work ok)
console.log(data1.length) // this should be 7 OK

object.data = data0.toString('utf-8', 0, 4)
console.log(object) // {hola:'mundo', data:'norm'} OK

var objectBuffer = new Buffer(JSON.stringify(object))
console.log(objectBuffer.length) // this should be 30 OK

object.data = data1.toString('utf-8', 0, 4)
console.log(object) // {hola:'mundo', data:'"norm'} OK

var objectBuffer = new Buffer(JSON.stringify(object))
console.log(objectBuffer.length) // this should be 30 NOT OK got 31 instead

2 个答案:

答案 0 :(得分:1)

您的代码末尾的JSON.stringify实际字符串为{"hola":"mundo","data":"\"nor"}。该字符串有31个字符,包括用于在\属性的字符串值内转义双引号的反斜杠(data)。反斜杠是"额外"字符。

答案 1 :(得分:1)

您可以为特殊字符使用自定义替换程序,并在JSON.stringify方法中传递该函数:

请参阅以下部分:“使用replacer参数JSON.stringify(javascriptObject,method)的示例;”

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


    function replacer(key, value) {
        if (typeof value === "string") {
            return undefined;
        }
        return value;
    }

    var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
    var jsonString = JSON.stringify(foo, replacer);