我目前正在開發一個項目,我需要將一些舊代碼轉換爲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;
}
讓我知道!謝謝!
Should'nt你建立一個經典的JavaScript對象,然後使用JSON.stringify? –
檢查了這一點:http://json.fastfrag.org/ –
@SteveB我想我只是應用到目前爲止我所知道的,並使這項工作,創建一個對象將是理想的,但我一直無法正確地做到這一點 –