jquery - JSON 数组的简单迭代

标签 jquery arrays wcf json iteration

更新了实际的 JSON 响应,上次搞砸了。

这是我使用 JSON 的第二天,我陷入了项目的第一步。

我创建了一个 WCF Rest 服务,它提供了此测试 json 响应。

[{
"busyEndTime":"\/Date(928164000000-0400)\/",
"busyStartTime":"\/Date(928164000000-0400)\/",
"endGradient":1.26743233E+15,
"startGradient":1.26743233E+15,
"status":"String content"

}]

我正在尝试读取此输出的内容并将该内容用于各种其他目的。 在内容中,我指的是“busyEndTime、busyStartTime”值等。

我在网上尝试了很多例子,但我的运气还是不好,

以下是我尝试阅读上述内容的方法,但失败了。

$('#btnGetTime').click(function () {
    $.ajax({
        cache: false,
        type: "GET",
        async: false,
        url: serviceAddress,
        dataType: "application/json; charset=utf-8",
        data: "{}",

 success: function (student) {

********* ********** 尝试 1

var obj = jQuery.parseJSON(student);
for (var i = 0; i < obj.length; i++) {
       alert(obj[i]);
}

********* *尝试2

var obj = eval("(" + student + ")");
for (var i = 0; i < obj.length; i++) {
      alert(obj[i]);
                            }

********* *****尝试 3

success: test(student)
.......
.....
function test(jObject) {
  var jArrayObject = jObject
  if (jObject.constructor != Array) {
      jArrayObject = new Array();
      jArrayObject[0] = jObject;
  }

********* *****尝试 4

success: test(student)
.......
.....
function test(jObject) {
    var jArrayObject = jObject
    for (var i = 1, n = jObject.length; i < n; ++i) {
         var element = jObject[i];
................
....................
} 

********* ******尝试5

                    $.each(jArrayObject, function (key, value) {
                        alert(key + ": " + value);
                    });
<小时/>

如果有人可以逐步指导如何像我上面那样读取 JSON 响应并迭代响应包含的数组并最终使用数组中的内容(至少是警报),我将非常感激键值对。

我想要的就是快速响应,随着时间的流逝,我对 jquery 失去了兴趣。 :(

最佳答案

更新:既然您已经发布了实际的 JSON 文本,下面是使用它的示例:

$.getJSON(url, function(data) {
  // jQuery will deserialize it into an object graph for
  // us, so our `data` is now a JavaScript object --
  // in this case, an array. Show how many entries we got.
  display("Data received, data.length = " +
          data.length);

  // Show the start and end times of each entry
  $.each(data, function(index) {
    display("Entry " + index +
            ": Start = " + this.busyStartTime +
            ", end = " + this.busyEndTime);
  });
});

Live copy

输出:

Loading JSON from /aduji4/4...
Data received, data.length = 1
Entry 0: Start = /Date(928164000000-0400)/, end = /Date(928164000000-0400)/

Note that the dates aren't automagically handled unless you use a "reviver" with the JSON parser that understands that particular date format. JSON has no date format of its own, but it has this concept of a "reviver" that can be used during the deserialization process to pre-process values.

jQuery's own JSON parser doesn't have the "reviver" feature, but you can download ones that do (there are three on Douglas Crockford's github page — Crockford being the inventor of JSON). Then you'd tell jQuery not to parse the JSON, and instead do it explicitly yourself. That would look like this:

// Start loading the JSON data
$.ajax({
  url: url,
  dataType: "text", // Tell jQuery not to try to parse it
  success: function(data) {

    // `data` contains the string with the JSON text.
    // Deserialize it. jQuery's own JSON parser doesn't
    // have the "reviver" concept, but this is where you
    // would use one that does, giving it the reviver.
    data = $.parseJSON(data);

    // Now we have the object graph (an array in this
    // case), show how many entries it has.
    display("Data received, data.length = " +
            data.length);

    // Show the start and end times of each entry
    $.each(data, function(index) {
      display("Entry " + index +
              ": Start = " + this.busyStartTime +
              ", end = " + this.busyEndTime);
    });
  },
  error: function() {
    display("Error loading JSON");
  }
});

Live copy

...当然你会使用其他 JSON 解析器而不是 $.parseJSON .

<小时/>

原始答案:

问题

i created a wcf rest service which gives this test json response.

这不是 JSON。您可以阅读 JSON here ,您可以验证您的 JSON 字符串 here 。我不太确定它是什么。它看起来很像 XML,但就像有人从树查看器或其他东西中获取了 XML(元素开头旁边的那些 - 符号)。

下面,我将展示该数据在 JSON 中的样子、如何使用它,然后如果您想使用 XML,则使用使用 XML 数据的相同示例。

JSON 格式的数据

以下是 JSON 中的内容:

{
    "ArrayOfBusyDateTime": [
        {
            "busyEndTime":   "2011-04-20T10:30:00",
            "busyStartTime": "2011-04-20T10:00:00",
            "endGradient":   0,
            "startGradient": 0,
            "status":        "busy"
        },
        {
            "busyEndTime":   "2011-04-20T13:00:00",
            "busyStartTime": "2011-04-20T12:00:00",
            "endGradient":   0,
            "startGradient": 0,
            "status":        "busy"
        }
    ]
}

请注意,类型(元素名称)已经消失,因为 JSON 没有元素名称的概念。 (如果您需要它们,您可以创建一个保存相关信息的键。)因此数组中的两个条目中的每一个都是 busyDateTime纯粹是因为处于 ArrayOfBusyDateTime 。但 JSON 的特点之一是它具有很强的可塑性,因此您可能更喜欢稍微不同的做法。

使用 JSON 数据

以下是使用该数据的示例:

$.getJSON(url, function(data) {
  // jQuery will deserialize it into an object graph for
  // us, so our `data` is now a JavaScript object.
  // Show how many entries we got in the array:
  display("Data received, ArrayOfBusyDateTime.length = " +
          data.ArrayOfBusyDateTime.length);

  // Show the start and end times of each entry
  $.each(data.ArrayOfBusyDateTime, function(index) {
    display("Entry " + index +
            ": Start = " + this.busyStartTime +
            ", end = " + this.busyEndTime);
  });
});

Live copy

输出:

Loading JSON from /aduji4...
Data received, ArrayOfBusyDateTime.length = 2
Entry 0: Start = 2011-04-20T10:00:00, end = 2011-04-20T10:30:00
Entry 1: Start = 2011-04-20T12:00:00, end = 2011-04-20T13:00:00

XML

For completeness, if your data really is XML, like this:

<ArrayOfBusyDateTime xmlns="http://schemas.datacontract.org/2004/07/RestServiceTest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <BusyDateTime>
    <busyEndTime>2011-04-20T10:30:00</busyEndTime>
    <busyStartTime>2011-04-20T10:00:00</busyStartTime>
    <endGradient>0</endGradient>
    <startGradient>0</startGradient>
    <status>busy</status>
  </BusyDateTime>
  <BusyDateTime>
    <busyEndTime>2011-04-20T13:00:00</busyEndTime>
    <busyStartTime>2011-04-20T12:00:00</busyStartTime>
    <endGradient>0</endGradient>
    <startGradient>0</startGradient>
    <status>busy</status>
  </BusyDateTime>
</ArrayOfBusyDateTime>

使用 XML 数据:

...那么您可以使用以下方法:

$.ajax({
  url: url,
  dataType: "xml",
  success: function(data) {
    // jQuery will deserialize it for us, so our
    // `data` is now an XML document. Wrap a jQuery
    // instance around it to make it easy to work with.
    data = $(data);

    // Show how many entries we got in the array
    var busyDateTimes = data.find("BusyDateTime");
    display("Data received, ArrayOfBusyDateTime length = " +
            busyDateTimes.length);

    // Show the start and end times of each entry
    busyDateTimes.each(function(index) {
      // In this loop, `this` will be the raw XML
      // element; again wrap a jQuery object around
      // it for convenience
      var $this = $(this);
      display("Entry " + index +
              ": Start = " + $this.find("busyStartTime").text() +
              ", end = " + $this.find("busyEndTime").text());
    });
  },
  error: function() {
    display("Error loading XML");
  }
});

Live copy

...虽然我不太使用 XML,但可能会提高一些效率(看起来很多东西都封装在 jQuery 实例中)。

输出:

Loading JSON from /aduji4/2...
Data received, ArrayOfBusyDateTime length = 2
Entry 0: Start = 2011-04-20T10:00:00, end = 2011-04-20T10:30:00
Entry 1: Start = 2011-04-20T12:00:00, end = 2011-04-20T13:00:00

关于jquery - JSON 数组的简单迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5757599/

相关文章:

javascript - jQuery 和 javascript 处理 xhtml

c++ - 在 C++ 中使用变量作为数组参数

.net - 创建提供 JSON 服务的 .NET 服务层 : WCF or MVC Content as JSON?

javascript - 如何查找和更新对象数组中的值?

wcf - WCF 中的 HttpContext

wcf - Azure WCF 服务使用 Azure WCF 服务

javascript - Microsoft Edge 扩展,如何操作 popup.html DOM

javascript - 在 JavaScript/JQuery 中将 HTML 元素转换为字符串

javascript - 获取 jQuery 可排序列表中列表项的顺序

javascript - 为什么这个函数不能处理这个特定的数组?