【问题标题】:How to traverse each property of JSON string如何遍历JSON字符串的每个属性
【发布时间】:2017-08-15 10:47:02
【问题描述】:

我有一个来自数据库的 JSON

[
  {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters": {
      "batter": [
        { "id": "1001", "type": "Regular" },
        { "id": "1002", "type": "Chocolate" },
        { "id": "1003", "type": "Blueberry" },
        { "id": "1004", "type": "Devil's Food" }
      ]
    },
    "topping": [
      { "id": "5001", "type": "None" },
      { "id": "5002", "type": "Glazed" },
      { "id": "5005", "type": "Sugar" },
      { "id": "5007", "type": "Powdered Sugar" },
      { "id": "5006", "type": "Chocolate with Sprinkles" },
      { "id": "5003", "type": "Chocolate" },
      { "id": "5004", "type": "Maple" }
    ]
  },
  {
    "id": "0002",
    "type": "donut",
    "name": "Raised",
    "ppu": 0.55,
    "batters": {
      "batter": [
        { "id": "1001", "type": "Regular" }
      ]
    },
    "topping": [
      { "id": "5001", "type": "None" },
      { "id": "5002", "type": "Glazed" },
      { "id": "5005", "type": "Sugar" },
      { "id": "5003", "type": "Chocolate" },
      { "id": "5004", "type": "Maple" }
    ]
  }
]

我正在尝试使用下面的 jquery ajax 调用方法遍历上面 JSON 的所有属性

$.ajax({
  url: 'myPage.aspx/CallingFunction',
  type: 'POST',
  data: '{}',
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function(data) {
    alert(data.d) // showing json is fine
    var MyData = $.parseJSON(data.d);
    for (i = 0; i < MyData.length; i++) {
      //How to travers all the properties defined in JSON
    }
  }
});

【问题讨论】:

标签: javascript jquery json


【解决方案1】:

Object.keys() 可以给你你想要的:

var i, key, value;
var keys = Object.keys(MyData);
for (i = 0; i < keys.length; i++) {
  key = keys[i];
  value = MyData[key];
  // ...
}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多