JavaScript JSON语法错误:无法识别的表达式

JavaScript JSON Syntax Error: Unrecognized Expression

本文关键字:识别 表达式 JSON 语法 错误 JavaScript      更新时间:2023-09-26

我试图使用jQuery来迭代这个JSON表达式中的对象:

[
    {
        "value": 609,
        "label": "Wyandotte, MI"
    },
    {
        "value": 3141,
        "label": "Wilmington, NC"
    }
]

使得每个对象由两个属性组成,值和标签。

这是我目前为止写的:

$(data).each(function () {
     alert('value: ' + this.value + ' label: ' + this.label);
});

但我一直得到一个错误:未捕获错误:语法错误,无法识别的表达式

有人能帮忙吗?

编辑:


示例中的数据变量是任意的。实际发生的是我得到了一个对象数组像这样:

data =
[
    locations: "[{"value":5626,"label":"Bensenville, IL"}]",
    notes: "Sample note"
]

然后调用data = JSON.parse(data);

然后我在data.locations上执行迭代,它产生了错误。

编辑(再一次):
https://jsfiddle.net/e2p7gdod/
我一直试图重现我所看到的。
我是这样生成返回结果的:

public JsonResult Foo()
{
    var data = new JObject();
    data["locations"] = "[{'value': 609,'label': 'Wyandotte, MI'},{'value': 3141,'label': 'Wilmington, NC'}]";
    data["supervisor"] = "John Doe";
    data["notes"] = "Sample note";
    return new JsonResult()
    {
        Data = JsonConvert.SerializeObject(data),
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
}

它看起来像你试图把一个JSON对象在data.locations,但你有语法错误。JSON中的字符串必须用双引号括起来,而不是单引号。

public JsonResult Foo()
{
    var data = new JObject();
    data["locations"] = "[{'"value'": 609,'"label'": '"Wyandotte, MI'"},{'"value'": 3141,'"label'": '"Wilmington, NC'"}]";
    data["supervisor"] = "John Doe";
    data["notes"] = "Sample note";
    return new JsonResult()
    {
        Data = JsonConvert.SerializeObject(data),
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
}

然后在Javascript中,当您想要迭代它时,您需要调用JSON.parse(data.locations):

var locations = JSON.parse(data.locations);
$.each(locations, function() {
    alert('value: ' + this.value + ' label: ' + this.label);
});

这应该是each的静态版本,传递数组(比在jQuery对象中包装数组更快,只是为了迭代它):

$.each(data, function () {
     alert('value: ' + this.value + ' label: ' + this.label);
});

注意:你当前的代码没有给出这个错误,看起来工作得很好:

http://jsfiddle.net/yk4wb7dv/

是否包含JQuery等?