2015-12-21 80 views
-2

請分享從JSON對象中使用值提取對象的所有可能方式。 考慮以下JSON例如:使用來自JSON對象的值提取對象(數據)

{ 
"ProductCollection": [ 
    { 
     "ProductId": "1239102", 
     "Name": "Power Projector 4713", 
     "Category": "Projector", 
     "SupplierName": "Titanium", 
     "Description": "A very powerful projector with special features for Internet usability, USB", 
     "WeightMeasure": 1467, 
     "WeightUnit": "g", 
     "Price": 856.49, 
     "CurrencyCode": "EUR", 
     "Status": "Available", 
     "Quantity": 3, 
     "UoM": "PC", 
     "Width": 51, 
     "Depth": 42, 
     "Height": 18, 
     "DimUnit": "cm" 
    }, 
    { 
     "ProductId": "2212-121-828", 
     "Name": "Gladiator MX", 
     "Category": "Graphics Card", 
     "SupplierName": "Technocom", 
     "Description": "Gladiator MX: DDR2 RoHS 128MB Supporting 512MB Clock rate: 350 MHz Memory Clock: 533 MHz, Bus Type: PCI-Express, Memory Type: DDR2 Memory Bus: 32-bit Highlighted Features: DVI Out, TV Out , HDTV", 
     "WeightMeasure": 321, 
     "WeightUnit": "g", 
     "Price": 81.7, 
     "CurrencyCode": "EUR", 
     "Status": "Discontinued", 
     "Quantity": 10, 
     "UoM": "PC", 
     "Width": 34, 
     "Depth": 14, 
     "Height": 2, 
     "DimUnit": "cm" 
    } 
] 
} 

如果我輸入 「角鬥士MX」,我想整個對象如下:

{ 
     "ProductId": "2212-121-828", 
     "Name": "Gladiator MX", 
     "Category": "Graphics Card", 
     "SupplierName": "Technocom", 
     "Description": "Gladiator MX: DDR2 RoHS 128MB Supporting 512MB Clock rate: 350 MHz Memory Clock: 533 MHz, Bus Type: PCI-Express, Memory Type: DDR2 Memory Bus: 32-bit Highlighted Features: DVI Out, TV Out , HDTV", 
     "WeightMeasure": 321, 
     "WeightUnit": "g", 
     "Price": 81.7, 
     "CurrencyCode": "EUR", 
     "Status": "Discontinued", 
     "Quantity": 10, 
     "UoM": "PC", 
     "Width": 34, 
     "Depth": 14, 
     "Height": 2, 
     "DimUnit": "cm" 
    } 

希望這個問題是清楚的。 TIA。

+0

您使用哪種語言? Java的? – BenC

+0

不..我想用Javascript。 – Venkat

回答

0

JSONArray對象有一個函數getJSONObject(int index),你可以通過編寫一個簡單的for循環遍歷所有的JSONObjects。 我假定你有JSON數組名productCollection如果不創建一個JSON數組,並做如下

for(int i = 0; productCollection.length(); i++){ 

      JSONObject myObj = productCollection.getJSONObject(i); 
    if(myObj .has("Gladiator MX")) { 
    //return your jsonobject else do something 
    } 
} 
+0

我會試試這個。但是,我使用了「$ .each()」。 – Venkat

0

首先你會分析你的JSON字符串轉換成Javascript對象使用JSON.parse

現在你的問題是在一個對象數組中找到一個特定的對象。您可以使用filter或手冊for循環:

var data = JSON.parse(jsonstring); 
var products = data["ProductCollection"]; 
var gladiatorMX; 

for (var i = 0; i < products.length; i++) { 
    var product = products[i]; 
    if (product["Name"] == "Gladiator MX") { 
     gladiatorMX = product; 
     break; 
    } 
}