当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - parsing JSON to javascript array

问题描述:

I get this JSON response from my service call :

[Object { __type="TestDTO:#TestServer.Data", DateCreated="/Date(1298357607157+0500)/", more...}, Object { __type="TestDTO:#TestServer.Data", DateCreated="/Date(1298357628953+0500)/", more...}]

and I want to use Jquery templates which require a javascript array

like :

var books = [

{ title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4.jpg" },

{ title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMshed.jpg" },

{ title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" },

{ title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "Asele.jpg" },

];

How can I convert the JSSON response to below format( please ignore the data) just format should be same.

I am using this in ajax success method:

 success: function (response) {

var tr = response.d;

var tests = tr.Tests;

$("#TestsTemplate").tmpl(tests).appendTo("#divTests");

.tmpl(tests) requires javascript array

Mu Jquery template looks like this :

Test Name: ${TestName}

Test Page: ${TestPage}

ID: ${ID}

Date Created: ${DateCreated}

Result: ${Result}

Status: ${Status}

 <div id="divTests">

</div>

and what I get from json is a DTO below

public class TestRunDTO

{

public long ID { get; set; }

public string TestSuiteName { get; set; }

public DateTime DateCreated { get; set; }

public int Result { get; set; }

public int Status { get; set; }

public List Tests { get; set; }

}

I want to show this test collection in TestRunDTO using jquery templates

Regards,

Asif Hameed

网友答案:

You can convert the returned JSON to some other object expected by $.tmpl. Use something like this:

/*
 * returnedObject - data returned by your service call
 */

var returnArr = [];
$.each(returnedObject, function() {
    var _tmp = {};
    _tmp.title = this.title;
    _tmp.price = this.price;
    _tmp.picture = this.picture;
    returnArr.push(_tmp);
});

$.('#template').tmpl(returnArr);

Hope this helps.

分享给朋友:
您可能感兴趣的文章:
随机阅读: