JSON.parse gives unexpected token error

I receive this data when I call my api

[{"DispatchNo":"95963","DispatchDate":"1/11/2018 12:00:00 AM","Complete":"Y","CustomerID":"214858","Name":"FELIX CONSTRUCTION COMPANY","Contact":"","Phone":"602-464-0011","ShipPhone":"480-528-9280","PurchaseOrder":"1642.14","OrderLoads":"5","OrderQty":"125","FreightUnitID":"T","FreightPay":"2.93","ProductID":"16272","MatlUnitID":"T","VehicleType1":" ","VehicleType2":" ","VehicleType3":" ","VehicleType4":" ","VehicleType5":" ","VehiclesOn":"N","LocationID":"5180-132","SchedStart":"1/11/2018 4:00:00 PM","Description1":"Spa #1 Hydraulics","Description2":"11140 N 136th ave","Description3":"7394","DestinationID":"DEL","ShipAddress1":"11140 N 136th Ave","ShipAddress2":"$2.93","ShipCity":"Surprise","ShipState":"AZ","ShipZip":"85379","NextLoadDateTime":"1/11/2018 4:50:00 PM","comment1":"Derek  480-528-9280","comment2":"Call Derek before dumping as location is next","comment3":"door to office "Call derek before Dumping."","expiredate":"11/24/2017 12:00:00 AM","NextLoadDateTime1":"1/11/2018 4:50:00 PM","DispatchDate1":"1/11/2018 12:00:00 AM","latitude":"33.5850506","longitude":"-112.3531363"}]

my controoller.js code where it indicates failure is:

var jsonString = result.data.replace(/\\/g, "\\");
                var orderFromApex = JSON.parse(jsonString);
                orderFromApex = orderFromApex.substring(0);
                //orderFromApex += '"';
                orderFromApex = JSON.parse(orderFromApex);

I get error SyntaxError: Unexpected token C in JSON at position 898 at JSON.parse () I believe it is failing at orderFromApex = JSON.parse(orderFromApex). I am also console logging orderFromApex which I have posted above. What is going on? is there a problem with my JSON response?

1 answer

  • answered 2018-01-11 20:52 Niklas Higi

    Your API seems to not escape characters correctly. " for example appears unescaped inside strings closing them before they should be closed.

    {"example": "Hello "World"!"} should instead be {"example": "Hello \"World\"!"}.

    Trying to parse the first example will throw SyntaxError: Unexpected token W in JSON at position 20. That's because the parser will look at the " before World and think Oh, the string is already over, what's this weird W doing after it?.