I'm trying to read a Json object that was serialized by JavaScriptSerializer Serialize .NET function. But I am getting invalid character error in JSON.parse. What am I missing?
This is the Json String generated by the function:
[
{
"Word":"areopagus",
"Definition":"Def 1",
"Rank":1
},
{
"Word":"areopagus",
"Definition":"Def 2",
"Rank":2
}
]
Controller:
[HttpGet]
public ActionResult GetWordDefinition(string word)
{
List<vwWordDefinition> w = db.vwWordDefinitions.Where(x => x.Word == word).OrderBy(x => x.Rank).ToList();
var json = new JavaScriptSerializer().Serialize(w);
return new ContentResult { Content = json, ContentType = "application/json" };
}
Javascript:
$(function () {
$('#btnViewDefinition').click(function () {
if ($('#searchString').val() != null) {
$.ajax({
type: "GET",
url: '@Url.Action("GetWordDefinition", "WordList")',
cache: false,
data: { word: $('#searchString').val() },
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
var jsonData = JSON.parse(result);
for (var i = 0; i < jsonData.length; i++) {
var w = jsonData[i];
console.log(w.Word);
console.log(w.Definition);
}
}
});
}
});
});
datatype: 'json'
instructs $.ajax()
to parse the response. The result
will already be an array of objects and not a JSON string. Your subsequent attempt to parse the array as a string is causing the error.
From the jQuery documentation:
"json": Evaluates the response as JSON and returns a JavaScript object
Note: This answer was cobbled together from the comments so I have marked it Community Wiki.