Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript、JSON、按名称引用_Javascript_Json - Fatal编程技术网

JavaScript、JSON、按名称引用

JavaScript、JSON、按名称引用,javascript,json,Javascript,Json,如何在JavaScript中引用JSON对象 我有一个来自Rest web服务的JSON响应,并试图通过JSON.Parse(response) 示例JSON: { "HotelListResponse":{ "customerSessionId":"", "numberOfRoomsRequested":1, "moreResultsAvailable":true, "cacheKey":"", "cacheLocati

如何在JavaScript中引用JSON对象

我有一个来自Rest web服务的
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?第二家酒店的名字是什么


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

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

var response = JSON.Parse(jsonString);
您应该可以这样访问它:

var customerSessionId = response.HotelListResponse.customerSessionId;

这是可行的解决方案

如您所见,您需要参考
HotellisResponse
, 因此,如果
var result
保存了json对象,那么可以使用

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

首先,您发布的JSON无效。我修好了it@ZekeDroid,如果我没有错的话,那么获取会话Id不应该是
jsonObject.hotellisterResponse.customerSessionId
?另外,JSON.parse会将JSON对象的字符串表示形式转换为对象,因此在插入之前确保它是字符串。你能公布你正在使用的实际代码吗?