2011-07-10 98 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);