带有JSON.parse的字符串中的字符无效

时间:2015-09-24 14:52:40

标签: javascript json parsing eval

有人可以帮我确定这个字符串的问题......

Visual Studio Escaped String

"({ID:[\"1\"],ElementID:[\"1\"],UserHashKey:[\"39f46b38-e4c5-4081-aba4-28158d271952\"],[new String(\"FirstName88\")]:[new String(\"Ryan\")],[new String(\"LastName89\")]:[new String(\"Leesh\")],[new String(\"Type90\")]:[new String(\"Dental\")],[new String(\"Test[\\\"\\\"]91\")]:[new String(\"Help Me\")],UserCreated:[\"rleesh@hotmail.com\"],Created:[\"9/23/2015\"],Updated:[\"9/23/2015\"]})"

Visual Studio Text Visualizer

({ID:["1"],ElementID:["1"],UserHashKey:["39f46b38-e4c5-4081-aba4-28158d271952"],[new String("FirstName88")]:[new String("Ryan")],[new String("LastName89")]:[new String("Leesh")],[new String("Type90")]:[new String("Dental")],[new String("Test[\"\"]91")]:[new String("Help Me")],UserCreated:["ryanleesh@hotmail.com"],Created:["9/23/2015"],Updated:["9/23/2015"]})

我收到eval(str)和JSON.parse(str)

的相同错误

无效字符

我知道问题来自以下[\" \"],但我无法弄清楚如何操纵它来传递解析引擎。

代码如下:

String.prototype.toFieldDef = function () {
    var str = '({' + this + '})';
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');

try {
    //str = JSON && JSON.parse(str) || $.parseJSON(str);
    str = eval(str);
} catch (e) {
    if (e instanceof SyntaxError) {
        try{
            str = eval('"'+str+'"')
        } catch (f) {
            if (f instanceof SyntaxError) {
                alert(f.message);
            }
        } 
    }
}

return str;

};

1 个答案:

答案 0 :(得分:0)

我看到的主要问题是某些对象键被指定为数组。考虑:

js> x="{[new String(\"FirstName88\")]:[new String(\"Ryan\")]}";
js> eval(x)
typein:2: SyntaxError: invalid label:
typein:2: {[new String("FirstName88")]:[new String("Ryan")]}
typein:2: ...........................^

用括号替换方括号无济于事,至少在使用JavaScript-C或v8时是这样。您要么必须使用字符串文字,要么以编程方式构造(或重构)要评估的字符串。

相关问题