json解析错误语法错误输入意外结束

时间:2022-07-09 22:54:22

I got the following piece of code

我得到了下面这段代码

function pushJsonData(productName) {
    $.ajax({
        url: "/knockout/SaveProduct",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: " { \"Name\" : \"AA\" } ",
        async: false,
        success: function () {
            loadJsonData();   
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
}

Notice that I hard coded the data value. The data get pushed into the database fine. However, I keep getting the error "parsing error syntax error unexpected end of input". I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

注意,我硬编码了数据值。数据被很好地插入到数据库中。然而,我不断地得到错误“解析错误语法错误,输入意外结束”。我确信我的数据符合正确的JSON语法。当我在Chrome检查网络时,保存产品请求显示数据是正确的。

{ "Name": "AA" }

This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

这个POST请求没有响应。所以我不知道解析错误从何而来。我试过使用火狐浏览器。同样的事情又发生了。

Can anyone give some idea as to what is wrong?

有人知道哪里出了问题吗?

Thanks,

谢谢,

P.S. Here is the controller code

这是控制器代码

namespace MvcApplJSON.Controllers
{
    public class KnockoutController : Controller
    {
        //
        // GET: /Knockout/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetProductList()
        {
            var model = new List<Product>();
            try
            {
                using (var db = new KOEntities())
                {
                    var product = from p in db.Products orderby p.Name select p;
                    model = product.ToList();
                }
            }
            catch (Exception ex)
            { throw ex; }
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public void SaveProduct (Product product)
        {
            using (var db = new KOEntities())
            {
                db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
                db.SaveChanges();
            }
        }
    }
}

6 个解决方案

#1


53  

Can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

不能肯定问题出在哪里。可能是一些不好的性格,可能是你在开始和结束时留下的空间,不知道。

Anyway, you should absolutely never be hardcoding your JSON as strings as you did. Instead the proper way to send JSON data to the server is to use a JSON serializer:

无论如何,绝对不应该像以前那样将JSON硬编码为字符串。相反,将JSON数据发送到服务器的正确方法是使用JSON序列化器:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

现在,在服务器上也要确保您有合适的视图模型来接收这个输入:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

和相应的行动:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

还有一件事。您已经指定了数据类型:“json”。这意味着您希望服务器返回JSON结果。控制器动作必须返回JSON。如果您的控制器动作返回一个视图,这可以解释您所得到的错误。当jQuery尝试解析来自服务器的响应时:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most casesusually you don't need to be setting the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for that is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

也就是说,在大多数情况下,在向ASP发出AJAX请求时,通常不需要设置dataType属性。净MVC控制器动作。原因是,当您返回特定的ActionResult(如ViewResult或JsonResult)时,框架将自动设置正确的Content-Type响应HTTP头。然后,jQuery将使用这个头来解析响应,并将其作为参数提供给已经解析的成功回调。

I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

我怀疑您在这里遇到的问题是您的服务器没有返回有效的JSON。它要么返回一些ViewResult或PartialViewResult,要么尝试在控制器操作中手工创建一些损坏的JSON(显然,除了使用JsonResult之外,您不应该这么做)。

Ohhhh, and one more thing that I just noticed that made my eyes bleed:

哦,还有一件事让我的眼睛流血了:

async: false,

Seriously? Please, NEVER EVER NEVER set this attribute to false. I am seeing people doing this over and over and over and over again. It's outrageous. Guys, if you set this attribute to false you are no longer doing AJAX. You are blocking/freezing the client browser during the entire execution of the request killing all the benefits that AJAX gives you. Just make a normal request in this case. Don't bother with javascript. If you want to do AJAX, then stop thinking in terms of procedural and sequential programming. Start thinking in terms of asynchronous events and callbacks.

严重吗?千万不要把这个属性设为false。我看到人们一遍又一遍的重复这个过程。这太过分了。伙计们,如果你把这个属性设置为false,你就不再做AJAX了。在整个请求执行过程中,您正在阻塞/冻结客户端浏览器,从而扼杀AJAX提供的所有好处。在这种情况下,只需发出一个正常的请求。别烦使用javascript。如果您想要使用AJAX,那么请停止考虑过程性和顺序性编程。开始考虑异步事件和回调。

#2


3  

I was using a Node http request and listening for the data event. This event only puts the data into a buffer temporarily, and so a complete JSON is not available. To fix, each data event must be appended to a variable. Might help someone (http://nodejs.org/api/http.html).

我正在使用一个节点http请求并监听数据事件。此事件仅将数据暂时放入缓冲区,因此无法获得完整的JSON。要进行修正,必须将每个数据事件附加到一个变量中。可能帮助别人(http://nodejs.org/api/http.html)。

#3


1  

For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"

对我来说,这个问题是由于名称/值对的单引号引起的。数据:“{“名称”:“AA”}”

Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"

一旦我将它更改为名称/值对的双引号,它就可以正常工作了……数据:'{"Name:"AA"}或类似…数据:“{ \“\”:\“AA \“}”

#4


0  

Try using single quotes,

尝试使用单引号,

data: '{"Name":"AA"}'

#5


0  

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

输入的意外结束意味着解析器已经提前结束。例如,它可能期望“abcd…”但是只看到abcd…wxy。

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

这可能是某个地方的输入错误,也可能是在应用程序的不同部分混合编码时出现的问题。

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

一个示例:假设您正在使用chrome.runtime.sendNativeMessage从本地应用程序接收数据:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

在调用回调之前,浏览器将尝试使用JSON解析消息。解析,如果所提供的字节长度与数据不匹配,则会导致“输入的意外结束”错误。

#6


0  

I did this and it solved this problem.

我做了这个,它解决了这个问题。

var data = JSON.parse(Buffer.concat(arr).toString());

var数据= JSON.parse(Buffer.concat(arr).toString());

PS: In Node JS

PS:在节点JS

#1


53  

Can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

不能肯定问题出在哪里。可能是一些不好的性格,可能是你在开始和结束时留下的空间,不知道。

Anyway, you should absolutely never be hardcoding your JSON as strings as you did. Instead the proper way to send JSON data to the server is to use a JSON serializer:

无论如何,绝对不应该像以前那样将JSON硬编码为字符串。相反,将JSON数据发送到服务器的正确方法是使用JSON序列化器:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

现在,在服务器上也要确保您有合适的视图模型来接收这个输入:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

和相应的行动:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

还有一件事。您已经指定了数据类型:“json”。这意味着您希望服务器返回JSON结果。控制器动作必须返回JSON。如果您的控制器动作返回一个视图,这可以解释您所得到的错误。当jQuery尝试解析来自服务器的响应时:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most casesusually you don't need to be setting the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for that is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

也就是说,在大多数情况下,在向ASP发出AJAX请求时,通常不需要设置dataType属性。净MVC控制器动作。原因是,当您返回特定的ActionResult(如ViewResult或JsonResult)时,框架将自动设置正确的Content-Type响应HTTP头。然后,jQuery将使用这个头来解析响应,并将其作为参数提供给已经解析的成功回调。

I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

我怀疑您在这里遇到的问题是您的服务器没有返回有效的JSON。它要么返回一些ViewResult或PartialViewResult,要么尝试在控制器操作中手工创建一些损坏的JSON(显然,除了使用JsonResult之外,您不应该这么做)。

Ohhhh, and one more thing that I just noticed that made my eyes bleed:

哦,还有一件事让我的眼睛流血了:

async: false,

Seriously? Please, NEVER EVER NEVER set this attribute to false. I am seeing people doing this over and over and over and over again. It's outrageous. Guys, if you set this attribute to false you are no longer doing AJAX. You are blocking/freezing the client browser during the entire execution of the request killing all the benefits that AJAX gives you. Just make a normal request in this case. Don't bother with javascript. If you want to do AJAX, then stop thinking in terms of procedural and sequential programming. Start thinking in terms of asynchronous events and callbacks.

严重吗?千万不要把这个属性设为false。我看到人们一遍又一遍的重复这个过程。这太过分了。伙计们,如果你把这个属性设置为false,你就不再做AJAX了。在整个请求执行过程中,您正在阻塞/冻结客户端浏览器,从而扼杀AJAX提供的所有好处。在这种情况下,只需发出一个正常的请求。别烦使用javascript。如果您想要使用AJAX,那么请停止考虑过程性和顺序性编程。开始考虑异步事件和回调。

#2


3  

I was using a Node http request and listening for the data event. This event only puts the data into a buffer temporarily, and so a complete JSON is not available. To fix, each data event must be appended to a variable. Might help someone (http://nodejs.org/api/http.html).

我正在使用一个节点http请求并监听数据事件。此事件仅将数据暂时放入缓冲区,因此无法获得完整的JSON。要进行修正,必须将每个数据事件附加到一个变量中。可能帮助别人(http://nodejs.org/api/http.html)。

#3


1  

For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"

对我来说,这个问题是由于名称/值对的单引号引起的。数据:“{“名称”:“AA”}”

Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"

一旦我将它更改为名称/值对的双引号,它就可以正常工作了……数据:'{"Name:"AA"}或类似…数据:“{ \“\”:\“AA \“}”

#4


0  

Try using single quotes,

尝试使用单引号,

data: '{"Name":"AA"}'

#5


0  

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

输入的意外结束意味着解析器已经提前结束。例如,它可能期望“abcd…”但是只看到abcd…wxy。

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

这可能是某个地方的输入错误,也可能是在应用程序的不同部分混合编码时出现的问题。

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

一个示例:假设您正在使用chrome.runtime.sendNativeMessage从本地应用程序接收数据:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

在调用回调之前,浏览器将尝试使用JSON解析消息。解析,如果所提供的字节长度与数据不匹配,则会导致“输入的意外结束”错误。

#6


0  

I did this and it solved this problem.

我做了这个,它解决了这个问题。

var data = JSON.parse(Buffer.concat(arr).toString());

var数据= JSON.parse(Buffer.concat(arr).toString());

PS: In Node JS

PS:在节点JS