I am trying to parse an API data that i receive via ajax. I have no control over the api json structure. When i try to parse it using this code i get this error:
json.parse:unexpected character
and no data output on divs.I spend past 2 days couldn't fix it. Could you guys tell me how to fix it.Thanks
data.html content:
"[\r\n {\r\n \"itemID\": \"1\",\r\n \"itemTitle\": \"First\",\r\n \"itemText\": \"first one\",\r\n \"ThumbUrl\": \"http://somesite.com/1.jpg\",\r\n \"itemContent\": null\r\n },\r\n {\r\n \"itemID\": \"2\",\r\n \"itemTitle\": \"Second\",\r\n \"itemText\": \" second one\",\r\n \"ThumbUrl\": \"http://somesite/2.jpg\",\r\n \"itemContent\": null\r\n }\r\n]"
javascript:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ajax() {
$.get("./data.html", function(data){
data = data.replace("\"[", "[");
data = data.replace("]\"", "]");
$("#area1").text(data);
// parse JSON response
var json = $.parseJSON(data);
console.log(json);
// then loop the single items
for(i in json)
{
// create HTML code
var div = "<div class=\"image\">\n" +
"<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=http://somesite.com/" + json[i].itemID + "')\">\n" +
"<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />\n" +
"</a>\n" +
"</div>\n";
$("#myDiv").append(div);
}
});
}
</script>
<body>
<button onclick="ajax()">test</button>
<br>orginal data:<br>
<textarea id="area1" rows="4" cols="50" ></textarea>
<div id='myDiv'></div>
</html>
console.log(json):
JSON.parse: unexpected character
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
Line 4
Finally I solved the problem by removing both quotations,\r\n and some other unnecessary things with following method:
data = data.replace("\"[", "[");
data = data.replace("]\"", "]");
data = data.replace(/\\r\\n/g, "");
data = data.replace(/\\/g, "");
data = data.replace("n\"", "");
data = data.replace("\")", "");
data = data.replace("\",", "");