繁体   English   中英

循环解析 JSON 数据

[英]Looping to Parse JSON Data

描述和目标:本质上,数据每 2 分钟不断生成到 JSON 数据中。 我需要做的是从提供的 JSON 数据中检索信息。 数据会不断变化。 一旦信息被解析,它需要被捕获到可以在其他函数中使用的变量中。

我被困在试图弄清楚如何创建一个 function 循环,将所有数据重新分配给存储的变量,这些变量以后可以在函数中使用。

示例信息:

var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},

{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};

function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
 //Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}

}

所以最终的结果需要是这样的:

shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18  }

商店[1]={}

您可以使用以下代码遍历 JSON 字符串,

      var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];

        for(var i=0;i<JSONstring.length;i++){
        var obj = JSONstring[i];
          for(var key in obj){
                 var attrName = key;
                 var attrValue = obj[key];

                //based on the result create as you need
            }
         }

希望这可以帮助...

好吧,您的 output 示例是不可能的。 您有什么是事物列表,但您使用的是 object 语法。

如果您真的希望这些项目采用列表格式而不是键值对,那么有意义的是:

shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]

要遍历 object 中的属性,您可以使用以下内容:

var properties = Array();
for (var propertyName in theObject) {
  // Check if it’s NOT a function
  if (!(theObject[propertyName] instanceof Function)) {
    properties.push(propertyName);
  }
}

不过老实说,我不太确定你为什么要把它放在不同的格式中。 json 数据已经差不多了,您可以通过 shop[0]["carID"] 获取该字段中的数据。

在我看来,您想提取 JSON object 的“商店”属性中的数据,以便您可以轻松引用商店的所有商品。 这是一个例子:

var json =
  {
    "data":
      {"shop":
        [
          {"itemName":"car", "price":30000},
          {"itemName":"wheel", "price":500}
        ]
      }
  },
  inventory = [];

// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
  inventory[i] = json.data.shop[i];
}

// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM