[英]Retrieve data from a local nested JSON objects
我做了一個小的測試頁面,看起來像這樣:
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<title>Get JSON Value</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<script>
var json = $.getJSON("../js/report.json", function(data)
{
var items = [];
$.each(data, function (key, value)
{
items.push(key + " " + value);
});
alert(items[3]);
});
</script>
</body>
</html>
它從本地服務器上存儲的本地JSON文件中提取數據。
JSON對象如下所示:
{
"reportTitle": "Results",
"inlineAssets": false,
"stats": {
"suites": 7,
"tests": 13,
"passes": 11,
"pending": 0,
"failures": 2,
"start": "2016-08-11T13:30:48.362Z",
"end": "2016-08-11T13:31:29.433Z",
"duration": 41071,
...
}
alert(items[2]);
給我stats [object Object]
alert(items[3]);
給我suites [object Object]
我可以檢索suites
, tests
和passes
嗎? 因此,警報的輸出將為suites 7
, tests 13
和passes 11
。
編輯:
理想情況下,我想將這些值存儲在它們自己的變量中,而不是僅將alert
或console.log
。
編輯david
在這里輸入圖片描述
編輯3:
我試過了:
console.log(items[2].suites);
=> undefined
您沒有將統計信息推送到項目數組。 這就是為什么您無法獲取數據的原因。 嘗試使其更簡單
var json = $.getJSON("../js/report.json", function(data) {
var stats = data.stats;
$.each(stats, function(key, val){
alert(key + " " + val)
});
});
這是一種檢索suites
, tests
和passes
。
檢索suites
數量=> items[3].stats.suites
檢索tests
數=> items[3].stats.tests
檢索passes
=> items[3].stats.passes
將括號內的3
替換為所需的索引號。
編輯
您可以忘記我上面的答案。 這是真正的答案。 我對您的代碼做了一些修改,以獲得所需的答案。
var items=[];
function recursive(data){
$.each(data, function (key, value)
{
if (value instanceof Object) {
recursive(value);
} else {
items.push(key + " " + value);
}
});
}
var json = $.getJSON("report.json", function(data)
{
recursive(data);
console.log(items[2]); // return 'suites 7'
console.log(items[3]); // return 'tests 13'
console.log(items[4]); // return 'passes 11'
});
由於對象內部有一個對象,因此我必須使用遞歸來跟蹤所有數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.