0

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!

Quiver
  • 1,351
  • 6
  • 33
  • 56
  • 1
    Can you please share the JSON result? – Emanuel Gianico Nov 24 '15 at 19:11
  • You could try using html encoding on the apostrophes, which should convert them to `'`. – maniak1982 Nov 24 '15 at 19:11
  • https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx – maniak1982 Nov 24 '15 at 19:12
  • This is a duplicate question. http://stackoverflow.com/questions/12042302/serializing-strings-containing-apostrophes-with-json-net – CloudyOne Nov 24 '15 at 19:12
  • 2
    *"As far as I can tell, I am getting a parser error because some of the data I am returning contains apostrophes."* If the data is serialized properly to JSON, then that shouldn't be a problem. Could the error be elsewhere? What does `kendo.data.DataSource` do with the data? – Felix Kling Nov 24 '15 at 19:13
  • 1
    @maniak1982 That worked, thanks! – Quiver Nov 24 '15 at 19:19
  • You might want to try using JsonNetResult instead of JsonResult. http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net – Jon Brian Skog Nov 24 '15 at 19:19
  • Probably this, already asked on Stackoverflow, will help you. http://stackoverflow.com/questions/29931237/how-can-i-return-a-well-formatted-201-with-express – Bottlehunter Nov 24 '15 at 19:21
  • Please post the actual JSON output. You can get that by navigating to the `/Hospital/GetHospitals` route in your browser. The answers are terrible workaround that make no sense. Something else is wrong here. – poke Nov 24 '15 at 19:31
  • @poke For some reason when I navigate to the correct URL in the browser it's just a blank page. But it is the right URL because that action gets hit when I debug it and navigate there. – Quiver Nov 24 '15 at 19:32
  • What does it show when you show the source of that page in your browser? Is there still no output? – poke Nov 24 '15 at 19:34
  • @poke Yeah still nothing. I am running Telerik Fiddler as well and it shows nothing is being returned when I go there. – Quiver Nov 24 '15 at 19:35
  • Then you know why the JavaScript is messing up there: It’s trying to parse nothing as JSON. – poke Nov 24 '15 at 19:36
  • Look in the developer tools of your browser. There should be a "Network" tab or something similar which should show what was returned from the service call. – Heretic Monkey Nov 24 '15 at 19:44
  • @poke What could be causing that issue? When debugging if I hover over `hospitals` it shows the data is there. But obviously it's not being returned as JSON. @MikeMcCaughan The response I get is "Failed to load response data" – Quiver Nov 24 '15 at 19:52
  • What version of ASP.NET MVC are you using? Do you get any logging output on the server side? – poke Nov 24 '15 at 19:54
  • @poke Yep I didn't even think to check the logs. I'm getting the error: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. – Quiver Nov 24 '15 at 19:56
  • @Quiver Thanks! I wrote the comments as an answer if you would like to mark it resolved. – maniak1982 Nov 24 '15 at 20:05

4 Answers4

1

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?

Community
  • 1
  • 1
Quiver
  • 1,351
  • 6
  • 33
  • 56
0

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

Erik Johnson
  • 858
  • 1
  • 7
  • 29
0

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.

Emanuel Gianico
  • 330
  • 6
  • 19
0

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

maniak1982
  • 707
  • 2
  • 7
  • 23