最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert string to JSON Object - Stack Overflow

programmeradmin1浏览0评论

timeline.js + MVC + Ajax + JSON

hello,

I have problem while converting string to Json Object

I have to display timeline on my webpage, I have used Timeline.js for the same, I am able to run the timeline using static data that is as following

Static Data

// Create a JSON data table
data = [
{
        'start': new Date(2010, 7, 23),
    'content': 'Conversation'
},
{
    'start': new Date(2010, 7, 23),
    'content': 'New Conversation'
},
{
    'start': new Date(2010, 7, 23),
    'content': 'Very New Conversation'
}

now when I do

alert(data);

it gives me

[object Object],[object Object],[object Object]

but now I have to display a data from the DB, so I am calling the following function on controller

GetTimeLine method on controller

public JsonResult GetTimeline()
{
      JsonResult jr = new JsonResult();
      var objtimeline = objEntities.Timelines.Where(tl => tl.StudentID == Sessions.StudentID).ToList().AsQueryable();
      String newstr = "[";
      foreach(var tml in objtimeline)
      {
            DateTime date1 = Convert.ToDateTime(tml.CalculatedDate);
            newstr += "{'start': new  Date("+date1.Year+","+date1.Month+","+date1.Day+","+date1.Hour+","+date1.Minute+","+date1.Second+"),'content':'"+tml.Description+"'},";
      }
      newstr = newstr.TrimEnd(',');
      newstr += "];";
      jr.Data = newstr;
      jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
      return jr;
}

function to call controller method

jQuery.ajax({
    type: "POST",
    url: "@Url.Content("~/Student/GetTimeline")",
    success: function (result) {
        data = result;
    },
});
alert(data);

it gives me the following alert

[{'start': new Date(2012,2,11,0,0,0),'content':'Parents meeting'},{'start': new Date(2012,2,15,0,0,0),'content':'Exam Meeting'}];

so the problem is with conversion of string to Json Object,

How can I convert string returned from controller to Json Object on my view...

timeline.js + MVC + Ajax + JSON

hello,

I have problem while converting string to Json Object

I have to display timeline on my webpage, I have used Timeline.js for the same, I am able to run the timeline using static data that is as following

Static Data

// Create a JSON data table
data = [
{
        'start': new Date(2010, 7, 23),
    'content': 'Conversation'
},
{
    'start': new Date(2010, 7, 23),
    'content': 'New Conversation'
},
{
    'start': new Date(2010, 7, 23),
    'content': 'Very New Conversation'
}

now when I do

alert(data);

it gives me

[object Object],[object Object],[object Object]

but now I have to display a data from the DB, so I am calling the following function on controller

GetTimeLine method on controller

public JsonResult GetTimeline()
{
      JsonResult jr = new JsonResult();
      var objtimeline = objEntities.Timelines.Where(tl => tl.StudentID == Sessions.StudentID).ToList().AsQueryable();
      String newstr = "[";
      foreach(var tml in objtimeline)
      {
            DateTime date1 = Convert.ToDateTime(tml.CalculatedDate);
            newstr += "{'start': new  Date("+date1.Year+","+date1.Month+","+date1.Day+","+date1.Hour+","+date1.Minute+","+date1.Second+"),'content':'"+tml.Description+"'},";
      }
      newstr = newstr.TrimEnd(',');
      newstr += "];";
      jr.Data = newstr;
      jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
      return jr;
}

function to call controller method

jQuery.ajax({
    type: "POST",
    url: "@Url.Content("~/Student/GetTimeline")",
    success: function (result) {
        data = result;
    },
});
alert(data);

it gives me the following alert

[{'start': new Date(2012,2,11,0,0,0),'content':'Parents meeting'},{'start': new Date(2012,2,15,0,0,0),'content':'Exam Meeting'}];

so the problem is with conversion of string to Json Object,

How can I convert string returned from controller to Json Object on my view...

Share Improve this question edited Oct 15, 2012 at 6:07 IT ppl asked Apr 14, 2012 at 13:08 IT pplIT ppl 2,6472 gold badges41 silver badges57 bronze badges 5
  • I think you need to take another look at JSON objects and the syntax for them. If it's wrapped in [ and ] in Javascript, it's an array, not an object (JSON or otherwise). – Anthony Grist Commented Apr 14, 2012 at 13:13
  • @AnthonyGrist: Having an array as the top-level object is valid JSON. (However, the quoted string is not, not with those single quotes and that new Date(...) in there.) – T.J. Crowder Commented Apr 14, 2012 at 13:14
  • @T.J.Crowder It would appear I'm the one who needs to take another look at the syntax, then! – Anthony Grist Commented Apr 14, 2012 at 13:20
  • @IT ppl: there's no such thing as a JSON object (well, there's the JSON object in some browsers, with the parseJSON and stringify methods, but that is decidedly not what you're asking about). There are JS objects, object literals, and JSON. The result of the AJAX request is a JSON string. – outis Commented Apr 14, 2012 at 13:21
  • @AnthonyGrist: Yeah, well, json is a bit unclear about it. The RFC is more explicit, saying specifically that the top level can be an object or an array. Interestingly, the ECMAScript5 specification goes further and says that it can be any JSON value (so that would include just a string or number on its own). – T.J. Crowder Commented Apr 14, 2012 at 13:25
Add a ment  | 

2 Answers 2

Reset to default 4

You're working too hard. Let the framework do it for you.

public JsonResult GetTimeline()
{
     var timeline = objEntities.TimeLines.Where( tl => tl.StudentID == Sessions.StudentID )
                                         .ToList() //required due to Convert call
                                         .Select( tl => new
                                          {
                                               start = Convert.ToDateTime(tl.CalculatedDate),
                                               content = tl.Description
                                          });
     return Json( timeline, JsonRequestBehavior.AllowGet );
}

Then either use getJSON (since you specifically allow gets) or specify dataType: 'json' in your request.

$.getJSON( '@Url.Action("gettimeline","student")', function(data) {
     alert(data);
});

What you have the server returning is not valid JSON. Or give your server-side code, it may be valid JSON which just defines a string rather than an object graph. In JSON:

  • All object keys must be in double quotes, not single quotes.
  • All strings must be in double quotes, not single quotes.
  • new Date(...) is not valid (JSON doesn't have any concept of dates).

I believe you want to build up an array (not a string) and assign that to jr.Data, and then let the JsonResult object handle the serialization for you (but I haven't done this in ASP MVC).

Once you have the server returning valid JSON, ensure that it's returning it with the correct Content-Type header (the value is application/json). When you do, jQuery will see that it's JSON and deserialize it into an object graph for you. If you can't or don't want to make your server return valid JSON, add dataType: 'json' to the ajax call to force it.

发布评论

评论列表(0)

  1. 暂无评论