简体   繁体   中英

Return JsonResult with apostrophes

As far as I can tell, I am getting a parser error because some of the data I am returning contains apostrophes.

Error I'm getting:

SyntaxError: Unexpected end of input at Object.parse (native) at jQuery.parseJSON...

My javascript:

var viewModel = kendo.observable({
    hospitalDataSource: new kendo.data.DataSource({
        transport: {
            read: {
                url: "/Hospital/GetHospitals",
                dataType: "json",
                type: "GET"
            },
            schema: {
                model: {
                    id: "Id",
                    fields: {
                        ProviderId: { type: "number" },
                        Name: { type: "string" },
                        Active: { type: "string" }
                    }
                }
            },
            errors: "errorMsg"
        },
        pageSize: 10,
        error: function (e) {
            toastr.options = {
                "positionClass": "toast-bottom-full-width"
            };
            toastr.error('There was an error:' + e.errors, 'Uh Oh!');
            this.cancelChanges();
        },
        serverPaging: false,
        serverFiltering: false,
        serverSorting: false
    }),
})

Controller JsonResult:

[HttpGet]
public JsonResult GetHospitals()
{
    var hospitals = hospitalService.GetAllHospitals();
    return Json(hospitals, JsonRequestBehavior.AllowGet);
}

As I mentioned above, I believe I'm getting the parser error because some of my data contains apostrophes. For example, Name might include the string Women and Children's Hospital

I'm still new to MVC/C# and Json so I'm not sure how to go about solving this. Is there a way to escape all of the apostrophes? Or is there something else I should be doing.

Let me know if anything I said is not clear. Thanks!

Thanks to the user poke I was able to resolve this issue. It ended up not being a problem with the apostrophes but rather that the JSON Result that I was trying to return was longer than the max value set by default in MVC.

I was able to use this answer to solve my problem: Can I set an unlimited length for maxJsonLength in web.config?

You need to escape those apostrophes first by using str.Replace("'", "\\\\'") . to replace occurrences of "'" with "\\'"

I don't thing that the problem is related to the apostrophes, because the json serializer should escape them if needed. Anyway, to replace them better do it before serializing your object's collection.

[HttpGet]
public JsonResult GetHospitals()
{
    var hospitals = hospitalService.GetAllHospitals();

    // Replaces the apostrophes from the hospital name
    foreach(var hospital in hospitals) {
        hospital.Name = hospital.Name.Replace("'", ""); 
    }

    return Json(hospitals, JsonRequestBehavior.AllowGet);
}

In this way JSON will be returned without the aphostrophes on the name.

You could try using html encoding on the apostrophes, which should convert them to '

Usually this is a problem with the JSON.parse() call or any functions that rely on it, as it doesn't escape apostrophes or quotation marks. It should be fine with HTML entities, however.

If you're accustomed to using eval() to parse JSON, you won't have seen it. But you should really use a JSON parser for reasons outlined here:

http://www.json.org/js.html

Microsoft's ASP.NET implementation of HTML Encoding is described here.

https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM