2011-08-02 18 views
1

如果我有這樣的外部JSON文件:配售HTTP地址javascript變量的JSON解析

{ 
"http://example.org/about" : 
    { 
     "http://purl.org/dc/elements/1.1/title" : [{"value" : "annas homepage" , "type" : "literal"}] 
    } 
} 

和獲取JSON文件中的書名這個外部jQuery腳本:

var a = 'http://example.org/about' 
var b = 'http://purl.org/dc/elements/1.1/title' 

$(document).ready(function() { 
    $("#trigger").click(function(event) { 
    $.getJSON('rdfjson.json', function(json) { 
     $('#meta').html('Title: ' + json.a.b[0].value); 
    }); 
    }); 
}); 

和HTML代碼:

<p>Click on the button to fetch data from json structure:</p> 
<div id="meta"> 
This text will be overwritten. 
</div> 
<input type="button" id="trigger" value="Load Data" /> 

爲什麼不工作?當我在json文檔和腳本中使用普通字符串時,它工作正常。

另外,我不明白我怎麼能在整個JSON文件迭代如果是這樣,例如,較複雜或元素有一個包含數據等等等長向量..

非常感謝!

回答

3

因爲你正在尋找一個名爲a對象成員,而不是一個對象的成員,其名稱是存儲在該值變量「a」

而不是使用 「點號」 的,使用「方括號

$('#meta').html('Title: ' + json[a][b][0].value); 

欲瞭解更多信息,請參見這裏:http://www.dev-archive.net/articles/js-dot-notation/

編輯:

如果JSON結構如下所示:

  1. 版本的一個:

    { 
        "http://example.org/about" : 
        { 
         "http://purl.org/dc/elements/1.1/title" : [{"value" : "annas homepage" , "type" : "literal"}] 
        } 
    } 
    
  2. 版二:

    { 
        "http://somewhereelse.com/something" : 
        { 
         "http://anotherplace.org/dc/blah-blah-blah/title" : [{"value" : "annas homepage" , "type" : "literal"}] 
        } 
    } 
    

例如總有一個對象,其中一個成員有一個成員

...你需要針對它:

$.getJSON('rdfjson.json', function(obj) { 
    for (var x in obj) { 
     if (obj.hasOwnProperty(x)) { 
     var obj2 = obj[x]; 

     for (var x in obj2) { 
      if (obj2.hasOwnProperty(x)) { 
       $('#meta').html('Title: ' + obj2[x][0].value); 
      } 
     } 
     } 
    } 
}); 

當然你可以在for環內添加條件語句,如果你知道路徑多一點點的信息,你需要遍歷:

$.getJSON('rdfjson.json', function(obj) { 
    for (var x in obj) { 
     // if you know you're looking for a key that begins with "http://" 
     if (obj.hasOwnProperty(x) && x.indexOf("http://") === 0) { 
     var obj2 = obj[x]; 

     for (var x in obj2) { 
      // Check that the value is an array of at least length 1, and whose 1st value has the property "value". 
      if (obj2.hasOwnProperty(x) && obj2[x] instanceof Array && obj2[x].length > 0 && obj2[x][0].value) { 
       $('#meta').html('Title: ' + obj2[x][0].value); 
      } 
     } 
     } 
    } 
}); 
+2

用於詳細說明解釋,而不僅僅是給出答案。 –

+0

有一個小問題,有沒有辦法獲得json結構的主題和謂詞名稱,而不是手動在腳本中輸入它,並將它賦予變量a和b?例如,如果json文件動態變化,我會需要這個。 – 3mpetri

+0

@ 3mpetri:我不確定你的意思...你能嘗試以另一種方式解釋/舉個例子嗎? 'json [a] [b] [0] .value'的'json'部分由'getJSON'的回調函數中的變量名決定......它獨立於返回的JSON結構。無論返回的JSON結構的佈局如何,'json'都將始終指向根元素...然後您將** a **和** b **更改爲引用所需對象的成員。 – Matt

0
$('#meta').html('Title: ' + json.a.b[0].value); 

應該

$('#meta').html('Title: ' + json[a][b][0].value);