1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import json 5 6 7 SRC_TABLE = { 8 "裝修快帳":{"transType":"交易類型", 9 "transDate":"交易日期",10 "currency ":"交易幣種",11 "inAcct":u"資金流入帳戶",12 "inAmount":"流入金額",13 "outAcct":"資金流出賬戶",14 "outAmount":"流出金額",15 "memo":"備忘",16 "category":"收支項目",17 "createTime":"建立時間"18 },19 }20 21 class JSON2TableBuilder:22 #-----------------------------------23 def __init__(self,jsonData,src):24 self._jsonData = jsonData25 self._rowList = [self._getDescriptionRow(src)]26 self._rowList = self._rowList + self._convertToList()27 28 #-----------------------------------29 def _getDescriptionRow(self,src):30 row = None31 if SRC_TABLE.has_key(src):32 row = SRC_TABLE[src]33 return row34 else:35 raise Exception("error: source error")36 37 #-----------------------------------38 def outputHtml(self):39 index = 040 html = ""41 count = len(self._rowList)42 while index < count:43 html += self.genRowHtml(index)44 index = index + 145 return '<table class="qbj_json_table">\n'+html+'</table>\n'46 47 #-----------------------------------48 def genRowHtml(self,index):49 row = self._rowList[index]50 cellValues = row.values()51 s = "" 52 for value in cellValues:53 s += "<td>"+self._sprintf(value)+"<td>"54 return "<tr>"+s+"<tr>\n"55 56 #-----------------------------------57 '''將json資料轉成對象並檢測'''58 def _convertToList(self):59 data = json.loads(self._jsonData)60 if type(data) not in (list,dict):61 raise Exception("error: input error")62 63 if type(data) is dict:64 data = [data]65 return data66 67 '''將其他類型轉換為string'''68 def _sprintf(self,field):69 if type(field) in (int,float):70 field = str(field)71 72 if type(field) is unicode:73 field = field.encode('utf8')74 75 if len(field)==0:76 field = " "77 78 return field79 80 '''測試入口'''81 if __name__ == "__main__":82 s = '''83 [84 {"transType":"收入","transDate":"2011-11-09","currency":"人民幣",85 "inAcct":"活期賬戶","inAmount":1000.0,"outAcct":"","outAmount":0,"memo":"10 月份工資收入",86 "category":"工薪","createTime":"2011-11-09 03:02:34.000"},87 {"transType":"收入","transDate":"2011-12-09","currency":"人民幣",88 "inAcct":"現金","inAmount":1000.0,"outAcct":"","outAmount":0,"memo":"11 月份工資收入",89 "category":"工薪","createTime":"2011-12-09 13:22:01.000"}90 ]91 '''92 93 builder = JSON2TableBuilder(s,"裝修快帳")94 s2 = builder.outputHtml()95 print s2