2014-09-18 29 views
-1

如何從JSON格式搜索關鍵字。使用jQuery或JavaScript如何使用javascript或jquery從JSON搜索文本

我有一個JSON內容。從那我需要搜索並獲得搜索關鍵字的ID。

關鍵詞: 「權威」=>我想獲得ID爲4

關鍵詞: 「基本」=>我想獲得ID爲3

{ 
"data": { 
    "1":[ 
    { 
    "id":"3", 
    "title":"my title", 
    "content":"this is very basic sample content" 
    }, 
    { 
    "id":"4", 
    "title":"My sample title and text", 
    "content":"renewed by a licensing authority may be signed by such officer by the State Government.<p></p>" 
    } 
    ] 
} 
} 
+2

http://stackoverflow.com/questions/5288833/how-to-search-json-tree-with-jquery – Quantico 2014-09-18 17:31:21

回答

0
 $(document).ready(function(){ 
     var content = { 
     "data": { 
      "1":[ 
      { 
      "id":"3", 
      "title":"my title", 
      "content":"this is very basic sample content" 
      }, 
      { 
      "id":"4", 
      "title":"My sample title and text", 
      "content":"renewed by a licensing authority may be signed by such officer by the State Government.<p></p>" 
      } 
      ] 
     } 
     }; 

     alert(returnContent("basic")); 

     function returnContent(keyword) 
     { 
      var returnValue = null; 
      $.each(content.data, function(key, value){ 
       $.each(value, function(key2, value2){ 
        if(value2.content.toString().indexOf(keyword) != -1) 
        { 
         returnValue = value2.id.toString(); 
        } 
       }); 
      }); 
      return returnValue; 
     } 


    }); 

你只需要在returnContent()函數中更改關鍵字你正在尋找

+0

如果我有巨大的內容,那麼這是不是適當的解決方案在..我想 – 2014-10-04 10:11:39

+0

數據量沒有在問題中指定... – 2014-10-04 14:37:55