1

我从 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。

4

2 回答 2

1

这并不复杂。aaData您可以为此使用 DataTables 。我假设您的 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
});

结果在此处输入图像描述

于 2013-05-30T12:42:57.057 回答
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 :)

http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx

问候

于 2013-05-29T19:49:30.097 回答