我从asana获取json,它是几个对象的对象(数据)。如何将数据作为数组?
{"data":{"id":5571422294129,"created_at":"2013-05-24T15:31:50.340Z","modified_at":"2013-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
我正在尝试使用aoColumns将其放入数据表中。如果不需要将“数据”转换为数组,请告诉我如何在没有它的数据表中使用此JSON。
答案 0 :(得分:1)
这并不复杂。您可以使用DataTables aaData
。我假设您的JSON包含多个"data":{..}, "data":{..}, "data":{..}
?
然后,将其视为测试数据:
var data = [
{"data":{"id":1571422294129,"created_at":"2010-05-24T15:31:50.340Z","modified_at":"2010-05-24T15:32:21.260Z","name":"testProject","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":2571422294129,"created_at":"2011-05-24T15:31:50.340Z","modified_at":"2011-05-24T15:32:21.260Z","name":"Project A","notes":"","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}},
{"data":{"id":3571422294129,"created_at":"2012-05-24T15:31:50.340Z","modified_at":"2012-05-24T15:32:21.260Z","name":"Project B","notes":"bla bla","archived":false,"workspace":{"id":5571305742112,"name":"TestITAT"},"followers":[{"id":5571289325327,"name":"John Doe"}]}}
];
HTML标记
<table id="test">
<thead>
<tr>
<th>archived</th>
<th>created_at</th>
<th>id</th>
<th>modified_at</th>
<th>name</th>
<th>notes</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
将JSON转换为aaData-array :
var aaData = [];
for (var i=0;i<data.length;i++) {
aaData.push([
data[i].data.archived,
data[i].data.created_at,
data[i].data.id,
data[i].data.modified_at,
data[i].data.name,
data[i].data.notes
]);
}
初始化表格
$('#test').dataTable({
"aaData": aaData
});
结果:
答案 1 :(得分:0)
我不确定你究竟想做什么,但是......
如果您尝试将JSON反序列化为数据表,您需要这样的东西。这将采用您的JSON并将其反序列化为一个对象,它不会完全适用于数据表,而是使用DataContract和DataMember属性修饰的自定义类。但我认为这对你来说可能是一个很好的起点。
Public static T DeSerialize<T>(string strJSON)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strJSON));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return (obj);
}
这是一篇关于序列化JSON的非常有用的文章。 HTH:)
此致