javascript json uncaught syntaxerror意外令牌非法

时间:2013-12-26 07:48:54

标签: javascript jquery json

我正在获取具有特殊字符的服务器响应json,如何从中删除此特殊字符。它尝试了replace()但它不起作用。我的json样本在这里

{
     "@tag":"1013170",
     "@title":"Holman Rd & Trestle Glen Rd",
     "@lat":"37.8067794",
     "@lon":"-122.2325773",
     "@stopId":"52750"
 }

3 个答案:

答案 0 :(得分:2)

尝试这样的事情

    var str =   '{"@tag":"1013170","@title":"Holman Rd & Trestle Glen Rd","@lat":"37.8067794","@lon":"-122.2325773","@stopId":"52750"}';
    console.log(str.replace(/@/g,''));

    //will give you
    {"tag":"1013170","title":"Holman Rd & Trestle Glen Rd","lat":"37.8067794","lon":"-122.2325773","stopId":"52750"}

顺便说一下你的json是有效的

var json ={"@tag":"1013170","@title":"Holman Rd & Trestle Glen Rd"};

//var json_obj = $.parseJSON(json);//don't do this because it already json.

console.log(json.@tag); // don't use this way

console.log(json['@tag']);// instead try this way

答案 1 :(得分:2)

您无法更改属性名称,必须使用新名称添加值并删除旧属性:

object = {
     "@tag":"1013170",
     "@title":"Holman Rd & Trestle Glen Rd",
     "@lat":"37.8067794",
     "@lon":"-122.2325773",
     "@stopId":"52750"
 }
for (var property in object) {
    if (object.hasOwnProperty(property)) {
        object[property.slice(1)]=object[property];
        delete object[property];
    }
}
console.log(object) will now give you
{tag: "1013170", title: "Holman Rd & Trestle Glen Rd", lat: "37.8067794", lon: "-122.2325773", stopId: "52750"}

答案 2 :(得分:0)

最后我用这条线读了json。

result['@tag']

它很简单,你可以从'。'读取json。符号和[],第二个也读取特殊字符。