Wednesday 29 October 2014

Unexpected Token when Parsing a JSON String Retrieved from a SharePoint Listitem

I'm working on a SharePoint based solution at moment, which uses AngularJS and REST calls to build the interface (UI).

In certain scenarios I need to save JSON strings into list item properties. This is easy enough. I can call JSON.stringify(myobject) to create a string representation of the JavaScript object, and then save the value to SharePoint using a REST call.

The problem is, when I retrieve the value back from SharePoint, certain characters are encoded using ISO/IEC 8859-1 encoding. For example, "{" becomes {

Example: see the eBriefRecommendationsForApproval property below



When I make a call to JSON.parse(myjsonstring), I get the error: "Error retrieving noting data  SyntaxError: Unexpected token & at Object.parse (native)"

A colleague suggested a method he'd used before to get around a similar issue, simply replacing the characters.

I'm not sure if this is the "correct" approach or not, but it works! I ended out with the following function to parse JSON strings that are returned from SharePoint,.

function parseJSONString(value) {
try{
var convertedValue = value.replace(/"/g,'"')
.replace(/{/g,'{')
.replace(/}/g,'}')
.replace(/:/g,':');
return JSON.parse(convertedValue);
}catch(e){
return null;
}
}


No comments:

Post a Comment