JavaScript,JSON,按名称引用

时间:2015-02-13 00:51:34

标签: javascript json

如何在JavaScript中引用JSON对象?

我有来自Rest网络服务的JSON响应,并尝试通过JSON

方式引用我已解析为JSON.Parse(response)的响应内容

示例JSON:

{  
   "HotelListResponse":{  
      "customerSessionId":"",
      "numberOfRoomsRequested":1,
      "moreResultsAvailable":true,
      "cacheKey":"",
      "cacheLocation":"",
      "cachedSupplierResponse":{  
         "@supplierCacheTolerance":"NOT_SUPPORTED",
         "@cachedTime":"0",
         "@supplierRequestNum":"101",
         "@supplierResponseNum":"",
         "@supplierResponseTime":"",
         "@candidatePreptime":"14",
         "@otherOverheadTime":"",
         "@tpidUsed":"",
         "@matchedCurrency":"true",
         "@matchedLocale":"true"
      },
      "HotelList":{  
         "@size":"20",
         "@activePropertyCount":"101",
         "HotelSummary":[  
            {  
               "name":"name1"
            },
            {  
               "name":"name2"
            }
         ]
      }
   }
}

我怎样才能引用customerSessionId?还有第二个HotelSummary的名字?

对于customerSessionId,我尝试过jsonObject.customerSessionId,返回undefined。对于第二个酒店摘要名称,我尝试了jsobObject.HotelList.HotelSummary[1].name,这也是未定义的。

2 个答案:

答案 0 :(得分:3)

给定上面解析的JSON字符串并将其分配给变量:

var response = JSON.Parse(jsonString);

您应该能够像这样访问它:

var customerSessionId = response.HotelListResponse.customerSessionId;

答案 1 :(得分:0)

这是工作解决方案fiddle

如您所见,您需要参考HotelListResponse, 因此,如果您的var result拥有您的json对象,那么您可以使用

获取值
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name