我正在尝试创建一个loadrunner'js'文件来从json中捕获一些数据。 json文件位于Web服务器上,这不是问题。我可以成功检索json。但是,我想从json文本返回一个特定的值。我试图在本地html页面上执行此操作,如下所示,但我总是收到一条错误消息:
错误是TypeError:无法读取未定义的属性“位置”
代码:
<!doctype html> <head></head><script>
function getdata()
{
var jsontext = '{"Locations":{"Location":[{"@id":"3649","@latitude":"51.758","@longitude":"-1.576","@country":"England","@zoomLevel":"10","@obsZoomLevel":"5","@type":"Observing Site","@name":"Brize Norton","@geohash":"gcnyknk2h"},{"@id":"3","@latitude":"50.9503","@longitude":"-1.3567","@country":"England","@zoomLevel":"11","@type":"Airport and Heliport","@name":"Southampton Airport","@geohash":"gcp1c5hp4"}]}}';
var stringifiedjson = JSON.stringify(jsontext).replace(/@/g, '_'); //convert to JSON string
var data = JSON.parse(stringifiedjson);
json.innerHTML=data;
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err){
message.innerHTML = "(1)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(2)Error is " + err;
}
try{
var newlocation0 = data.Locations.Location[0]._id;
output.innerHTML=newlocation0;
return;
}
catch(err) {
message.innerHTML = message.innerHTML + "(3)Error is " + err;
}
}
</script>
<body>
Error Messages:
<p id="message"></p>
<BR><BR>
JSON Input:
<p id="json"></p>
<BR><BR>
Output:
<p id="output"></p>
<button onclick="getdata()">Check</button>
<button onclick="location.reload();">Reload</button>
</body>
我尝试了[0]和[1]符号的不同组合,但我无法获得json右侧部分的输出。
答案 0 :(得分:1)
jsontext最初是一个字符串
var jsontext = '{"Locations":{"Location":[{"@id":"3649","@latitude":"51.758","@longitude":"-1.576","@country":"England","@zoomLevel":"10","@obsZoomLevel":"5","@type":"Observing Site","@name":"Brize Norton","@geohash":"gcnyknk2h"},{"@id":"3","@latitude":"50.9503","@longitude":"-1.3567","@country":"England","@zoomLevel":"11","@type":"Airport and Heliport","@name":"Southampton Airport","@geohash":"gcp1c5hp4"}]}}';
你已将该字符串包装在另一个字符串中
var stringifiedjson = JSON.stringify(jsontext).replace(/@/g, '_');
结果字符串看起来像这样
""{\"Locations\":{\"Location\":[{\"_id\":\"3649\",\"_latitude\":\"51.758\",\"_longitude\":\"-1.576\",\"_country\":\"England\",\"_zoomLevel\":\"10\",\"_obsZoomLevel\":\"5\",\"_type\":\"Observing Site\",\"_name\":\"Brize Norton\",\"_geohash\":\"gcnyknk2h\"},{\"_id\":\"3\",\"_latitude\":\"50.9503\",\"_longitude\":\"-1.3567\",\"_country\":\"England\",\"_zoomLevel\":\"11\",\"_type\":\"Airport and Heliport\",\"_name\":\"Southampton Airport\",\"_geohash\":\"gcp1c5hp4\"}]}}""
解析一次返回内部JSON字符串
var data = JSON.parse(stringifiedjson);
再次从字符串解析中获取对象
data = JSON.parse(data);
OR
首先不需要JSON.stringify,你可以使用replace方法。