SinisterPenguin
SinisterPenguin

Reputation: 1618

Loop through JSON Data?

I'm trying to get a simple page to pull data from SQL Server via a MVC controller using Json.Net

(Sorry for the dirty code - my day job is a SQL Server Dev\DBA.)

Controller:

dataAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
string strjson = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
return Json(strjson,JsonRequestBehavior.AllowGet);

Index.cshtml:

$.getJSON("/Test/MikeTest", {}, 
        function (myData) {
            alert(myData);
            $.each(myData,function(key,data) {
            alert(key + ":" + data);
        })

returned JSON:

[{"DateTime":"2013-12-02T12:40:57.387","message":"simple test"}] 

When I loop through the JSON data each iteration returns a single character rather than key/name pairs.

Presumably I'm doing something daft & not returning/typing the data correctly - any simple pointers much apprecaited!

Upvotes: 0

Views: 415

Answers (1)

The response from $.getJSON probably is a string, try using "JSON.parse" to make the response an actual object.

Something like:

$.getJSON("/Test/MikeTest", {}, 
    function (myData) {
        alert(myData);
        myDataObj = JSON.parse(myData);
        $.each(myDataObj,function(key,data) {
           alert(key + ":" + data);
        })
 });

Upvotes: 1

Related Questions