jQuery - 在json中找到某些属性

时间:2011-10-29 10:46:56

标签: jquery json

我需要能够识别JSON响应的某些属性,这些属性并不总是以相同的方式格式化。该示例的片段是:

{
   "Attributes" : [
      {
         "Value" : "4 bedrooms",
         "DisplayName" : "Bedrooms",
         "Name" : "bedrooms"
      },
      {
         "Value" : "2 bathrooms",
         "DisplayName" : "Bathrooms",
         "Name" : "bathrooms"
      },
      {
         "Value" : "House",
         "DisplayName" : "Property type",
         "Name" : "property_type"
      },
      {
         "Value" : "$780,000",
         "DisplayName" : "Rateable value",
         "Name" : "rateable_value"
      },
      {
         "Value" : "Price by negotiation",
         "DisplayName" : "Price",
         "Name" : "price"
      },
      {
         "Value" : "13 Wellswood Way\r\nLower Shotover\r\nQueenstown-Lakes\r\nOtago",
         "DisplayName" : "Location",
         "Name" : "location"
      },
      {
         "Value" : "Queenstown-Lakes",
         "DisplayName" : "District",
         "Name" : "district"
      },
      {
         "Value" : "Lower Shotover",
         "DisplayName" : "Suburb",
         "Name" : "suburb"
      },
      {
         "Value" : "Otago",
         "DisplayName" : "Region",
         "Name" : "region"
      },
      {
         "Value" : "254m²",
         "DisplayName" : "Floor area",
         "Name" : "floor_area"
      },
      {
         "Value" : "1690m²",
         "DisplayName" : "Land area",
         "Name" : "land_area"
      },
      {
         "Value" : "CBM959",
         "DisplayName" : "Property ID#",
         "Name" : "property_id"
      },
      {
         "Value" : "playground,tennis,hiking,biking,historic bridge walk,buses,5 mins to shops.",
         "DisplayName" : "In the area",
         "Name" : "in_the_area"
      },
      {
         "Value" : "Large double garage.Plenty off-street parking.Extra for boat+ etc.",
         "DisplayName" : "Parking",
         "Name" : "parking"
      }
   ]
}

正如您所看到的,每个属性都重复了Name,DisplayName和Value。我不知道该怎么做是通过这些属性找到一个特定的属性。例如,我如何获得浴室的价值?

感谢您的帮助 亚当

3 个答案:

答案 0 :(得分:2)

示例 -

$(data.Attributes).each(function(index, element){
    if(element.Name == 'bathrooms')
        console.log(element.Value);
})

演示 - http://jsfiddle.net/PktXh/

答案 1 :(得分:1)

function getAttributesByName(arr,name){
    for(var i=0,l=arr.length;i<l;i++)
        if(arr[i].Name === name)
            return arr[i];
    return null;            
}

更多jquery方法:

function getAttributesByName(arr,name){
   var result = null;
   $.each(arr,function(){
       if(this.Name === name)
           result = this;
   });
   return result;
}

答案 2 :(得分:0)

这是:

var a = data.Attributes;
for(var i in a) {
    if(a.hasOwnProperty(i) && a[i].Name == 'bathrooms')
      return a[i].Value;
}