JSON 数组的简单迭代

发布于 2024-11-03 01:46:57 字数 2348 浏览 1 评论 0 原文

使用实际的 JSON 响应进行了更新,上次搞砸了。

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

我创建了一个 wcf 休息服务,它提供了此测试 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) {

***********< em>******** 尝试 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];
................
....................
} 

******** ******* Try5

                    $.each(jArrayObject, function (key, value) {
                        alert(key + ": " + value);
                    });

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

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

Updated with actual JSON Response, Messed up last time.

It is my second day with JSON, and i am stuck at the first step of my project.

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

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

}]

i am trying to read the content of this output and use the content for various other purposes.
By content i am referring to the "busyEndTime, busyStartTime" values etc.

I have tried numerous examples on the net, but my bad luck continues,

following are the ways i tried to read the above, but failed.

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

 success: function (student) {

******************* Try 1

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

********** Try 2

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

**************Try 3

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

**************Try 4

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

*************** Try5

                    $.each(jArrayObject, function (key, value) {
                        alert(key + ": " + value);
                    });

I would really appreciate if some one could guide step by step, of how to read the JSON response like i have above and iterate over the array that the response contains and finally use the content that lies in the array, at least alert the key value pairs.

A quick response is all i want, i am loosing interest in jquery with each passing minute. :(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终陌 2024-11-10 01:46:57

更新:既然您已经发布了实际的 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)/

请注意,除非您将“reviver”与可理解该特定日期格式的 JSON 解析器一起使用,否则不会自动处理日期。 JSON 没有自己的日期格式,但它具有“reviver”的概念,可以在反序列化过程中使用它来预处理值。

jQuery 自己的 JSON 解析器没有“reviver”功能,但您可以下载具有“reviver”功能的解析器(Douglas Crockford 的 github 页面 —Crockford 是 JSON 的发明者)。然后你会告诉 jQuery 解析 JSON,而是自己显式地解析。看起来像这样:

// 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


原始答案

问题

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

那不是 JSON。您可以在此处阅读 JSON 内容,并且可以验证您的 JSON 字符串此处。我不太确定它是什么。它看起来很像 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

为了完整起见,如果您的数据确实如此是 XML,如下所示:

<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

Update: Now that you've posted the actual JSON text, here's an example of using it:

$.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

Output:

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

...except of course you'd use some other JSON parser rather than $.parseJSON.


Original answer:

The problem

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

That's not JSON. You can read up on JSON here, and you can validate your JSON strings here. I'm not quite sure what it is. It looks a lot like XML, but like someone took the XML from a tree viewer or something (those - symbols next to the beginnings of elements).

Below, I'll show what that data might look like in JSON, how you would work with it, and then if you want to work with XML instead, the same example using XML data.

Your data in JSON format

Here's an idea of what that might look like in 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"
        }
    ]
}

Note that the types (element names) have gone, because JSON has no concept of element names. (If you want them, you can create a key that holds the relevant information.) So each of the two entries in the array is a busyDateTime by virtue purely of being in the ArrayOfBusyDateTime. But one of the things about JSON is that it's very malleable, so you may prefer to do it slightly differently.

Working with that JSON data

Here's an example of using that data:

$.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

Output:

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>

Working with XML data:

...then here's how you might work with that:

$.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

...although I don't work with XML much, could be some efficiencies to be had (seems like a lot of wrapping things up in jQuery instances).

Output:

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
二货你真萌 2024-11-10 01:46:57

对我来说它看起来不像 JSON!它看起来像 XML。

JSON 非常简单,记录如下: http://www.json.org/

您可能拥有的内容发现可能是对 WCF 失去兴趣的一个原因,但不是对 JSON/javascript/jQuery 失去兴趣。

It doesn't look like JSON to me! It looks like XML.

JSON is incredibly simple, and is documented here: http://www.json.org/

What you might have discovered might be a reason to lose interest in WCF, but not in JSON/javascript/jQuery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文