2011-07-10 97 views
0

描述和目标: 本质数据每隔2分钟到JSON数据被不断地生成。我需要做的是从提供的JSON数据中检索信息。数据将不断变化。信息解析后,需要将其捕获到可用于其他功能的变量中。循环解析JSON数据

我被困在试图找出如何创建一个函数有一个循环,重新分配所有的数据到可以稍后在函数中使用存储的变量是什么。

实施例的信息:

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] = {}

+0

你应该看看很简单[JSON-语法](http://www.json.org/) – Saxoier

回答

0

那么,你的输出示例是不可能的。你有什么是事物的列表,但你使用的是对象语法。

什么会,而不是意义,如果你真的想以列表格式而不是键值对这些项目会是这样:

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

对于通过性能在一个对象,你可以使用这样的循环:

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

老实说,我不确定你为什么要把它放在一个不同的格式。 JSON数据已然是因为它得到一样好,你可以做网店[0] [“carID”]来获得该字段中的数据。

+0

反正是有这些信息转移到其他可用的变量。 – user763349

+0

请点我在正确的方向。基本上我需要返回的事情的清单到一个对象 – user763349

+0

,我在第二块给的确会放的东西的清单到阵列中的代码。 – Case

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

希望这有助于...

0

像你想在“商店”属性提取数据,这听起来我的JSON对象,以便您可以轻松引用该商店的所有商品。这里有一个例子:

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);