2013-07-03 107 views
0

我目前正在開發一個項目,我需要將一些舊代碼轉換爲json對象。我們從sql查詢中獲取結果集,並將其返回的類別作爲json返回。我不太熟悉javascript,更不用說json了,所以我不確定最簡單的方法是什麼。下面是我需要改變成JSON的功能:將html轉換爲Json對象

function createOutputCategories(){ 
try 
    { 
     output = 
       "<html>" + 
       "<head>" + 
       "<title>" + 
       "You can find it!" + 
       "</title>" + 
       "</head>" + 
       "<body bgcolor='#CED3F3'>" + 
       "<a href='" + url + "file.xsjs?parent=1'>" + 
       "</a>" + 
       "<br><br>"; 
     if(parent === "1"){ 
      output = output + "<h3><font color='#AAAAAA'>Home</font>"; 
     }else{ 
      output = output +"<a href='javascript:history.back()'>" + 
      "<h3>Back"; 
     } 
     output = output + 
       "</h3>" + 
       "</a>" + 
       "<h1>" + 
       "Categories:" + 
       "</h1>"; 

     while(rs.next()){ 
      if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0"){ 
       output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>"; 
      }else{ 
       output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>"; 
      } 
     } 
}catch(Exception){ 
    $.response.contentType = "text/plain"; 
    $.response.setBody("Failed to retreive data"); 
    $.response.status = $.net.http.INTERNAL_SERVER_ERROR; 
} 

這裏是我有這麼遠,但我不返回有效的JSON對象:如果我需要提供別的請

function createOutputCategories(){ 

try{ 
    output = 
     "category: {name = \"" + parent + "\"; description = \"\"}"; 

    output = output + 
     "subcategories: [ "; 

    while(rs.next()){ 
     output = output + 
      "{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}"; 
     } 
    output = output + 
     "];"; 
    } 
catch(Exception){ 
    $.response.contentType = "text/plain"; 
    $.response.setBody("Failed to retreive data"); 
    $.response.status = $.net.http.INTERNAL_SERVER_ERROR; 
} 

讓我知道!謝謝!

+0

Should'nt你建立一個經典的JavaScript對象,然後使用JSON.stringify? –

+0

檢查了這一點:http://json.fastfrag.org/ –

+0

@SteveB我想我只是應用到目前爲止我所知道的,並使這項工作,創建一個對象將是理想的,但我一直無法正確地做到這一點 –

回答

3

你想輸出一個JavaScript對象的字符串?

構造對象:

var category=new Object(); 
category.name="Name"; 
category.description="My lovely description"; 
category.subcategories=[]; 

var subCat=new Object(); 
subCat.catid=1; 
subCat.catname="My subcat"; 

category.subcategories.push(subCat); 

或者,您可以使用文字構造對象:

var category={ 
    name:"Name", 
    description:"My lovely description", 
    subcategories:[ 
     {catid:1,catname:"My subcat"} 
    ] 
}; 

然後返回對象的字符串。

return JSON.stringify(category); 

,如果你需要更多的幫助,以JavaScript對象的引用: http://www.w3schools.com/js/js_objects.asp

+0

我認爲最好是創建一個對象,然後將其作爲字符串返回以供我使用。我試圖學習/理解/應用所有這一切,因爲我去哈哈 –

+0

我擴大了我的JavaScript示例有點向你展示創建一個對象的不同方式。 –

+0

我要試一試,謝謝! –