[英]JavaScript, JSON, referencing by name
How do you reference a JSON object in JavaScript? 如何在JavaScript中引用JSON对象?
I have a JSON
response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON
by way JSON.Parse(response)
我有一个来自Rest Web服务的
JSON
响应,并尝试引用通过JSON.Parse(response)
解析为JSON
的JSON.Parse(response)
Sample JSON: 样本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"
}
]
}
}
}
How can I, for example reference the customerSessionId? 例如,我如何引用customerSessionId? And the second HotelSummary name?
还有第二个HotelSummary名称?
For customerSessionId I have tried jsonObject.customerSessionId
which returns undefined. 对于customerSessionId,我尝试了
jsonObject.customerSessionId
,它返回未定义。 For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name
which is undefined too. 对于第二个酒店摘要名称,我尝试了
jsobObject.HotelList.HotelSummary[1].name
,该名称也未定义。
Given the JSON string above parsed and assigned to a variable as such: 给定上面解析的JSON字符串并将其分配给这样的变量:
var response = JSON.Parse(jsonString);
you should be able to access it like this: 您应该可以这样访问它:
var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle 这里的工作解决方案小提琴
As you can see, you need to reference HotelListResponse
, so if your var result
holds your json object, then you can fetch the values by using 如您所见,您需要引用
HotelListResponse
,因此,如果您的var result
包含您的json对象,那么您可以使用来获取值
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.