JSON記述のリストをHTML表クラスに変換(符号化スタイルはだいぶ良くなったと思います)

15457 ワード

 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 = jsonData

25         self._rowList = [self._getDescriptionRow(src)]

26         self._rowList = self._rowList + self._convertToList()

27 

28     #-----------------------------------

29     def _getDescriptionRow(self,src):

30         row = None

31         if SRC_TABLE.has_key(src):

32             row = SRC_TABLE[src]

33             return row

34         else:

35             raise Exception("error: source error")

36         

37     #-----------------------------------

38     def outputHtml(self):

39         index = 0

40         html = ""

41         count = len(self._rowList)

42         while index < count:

43             html += self.genRowHtml(index)

44             index = index + 1

45         return '<table class="qbj_json_table">
'+html+'</table>
' 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>
" 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 data 66 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 = "&nbsp;" 77 78 return field 79 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