2016-03-02 207 views
0
添加額外的對象標識符

我使用tableToJson,您可能會或可能不熟悉,到錶轉換成JSON(IVE包括它的代碼在這裏,如果你不知道它)。夠簡單。輸出是完全如預期,看起來像:表以JSON - >從<tr> IDS

{"data":[ 
{"Time":"6:30am - 8:30am","Monday":"","Tuesday":"Maths","Wednesday":"","Thursday":"","Friday":""}, 
{"Time":"11:15am - 12:45pm","Monday":"Maths","Tuesday":"","Wednesday":"English","Thursday":"","Friday":""}, 
{"Time":"3:00pm - 5:00pm","Monday":"","Tuesday":"","Wednesday":"English","Thursday":"","Friday":""}, 
{"Time":"5:00pm - 7:00pm","Monday":"","Tuesday":"Science","Wednesday":"","Thursday":"","Friday":""}, 
{"Time":"7:00pm - 9:00pm","Monday":"","Tuesday":"Science","Wednesday":"","Thursday":"","Friday":""}] 
} 

不過,我需要擴展它來把每<tr>的#ids所以JSON樣子:(假設表HTML是<tr id="session 1"></tr>等)

{ 
"data":{ 
"session 1":{"Time":"6:30am - 8:30am","Monday":"","Tuesday":"sdfsdf","Wednesday":"","Thursday":"","Friday":""}, 
"session 2":{"Time":"11:15am - 12:45pm","Monday":"sdfsdfsdf","Tuesday":"","Wednesday":"","Thursday":"","Friday":""}, 
"session 3":{"Time":"3:00pm - 5:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""}, 
"session 4":{"Time":"5:00pm - 7:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""}, 
"session 5":{"Time":"7:00pm - 9:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""} 
} 
} 

供參考的tableToJson的代碼如下所示:

(function($) { 
    'use strict'; 

    $.fn.tableToJSON = function(opts) { 

    // Set options 
    var defaults = { 
     ignoreColumns: [], 
     onlyColumns: null, 
     ignoreHiddenRows: true, 
     ignoreEmptyRows: false, 
     headings: null, 
     allowHTML: false, 
     includeRowId: false, 
     textDataOverride: 'data-override', 
     textExtractor: null 
    }; 
    opts = $.extend(defaults, opts); 

    var notNull = function(value) { 
     return value !== undefined && value !== null; 
    }; 

    var ignoredColumn = function(index) { 
     if(notNull(opts.onlyColumns)) { 
     return $.inArray(index, opts.onlyColumns) === -1; 
     } 
     return $.inArray(index, opts.ignoreColumns) !== -1; 
    }; 

    var arraysToHash = function(keys, values) { 
     var result = {},index=0, name = 'test'; 
     $.each(values, function(i, value) { 
     // when ignoring columns, the header option still starts 
     // with the first defined column 
     if (index < keys.length && notNull(value)) { 
      result[ keys[index] ] = value; 
      index++; 
     } 
     }); 
     return result; 
    }; 

    var cellValues = function(cellIndex, cell, isHeader) { 
     var $cell = $(cell), 
     // textExtractor 
     extractor = opts.textExtractor, 
     override = $cell.attr(opts.textDataOverride); 
     // don't use extractor for header cells 
     if (extractor === null || isHeader) { 
     return $.trim(override || (opts.allowHTML ? $cell.html() : cell.textContent || $cell.text()) || ''); 
     } else { 
     // overall extractor function 
     if ($.isFunction(extractor)) { 
      return $.trim(override || extractor(cellIndex, $cell)); 
     } else if (typeof extractor === 'object' && $.isFunction(extractor[cellIndex])) { 
      return $.trim(override || extractor[cellIndex](cellIndex, $cell)); 
     } 
     } 
     // fallback 
     return $.trim(override || (opts.allowHTML ? $cell.html() : cell.textContent || $cell.text()) || ''); 
    }; 

    var rowValues = function(row, isHeader) { 
     var result = []; 
     var includeRowId = opts.includeRowId; 
     var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false; 
     var rowIdName = (typeof includeRowId === 'string') === true ? includeRowId : 'rowId'; 
     if (useRowId) { 
     if (typeof $(row).attr('id') === 'undefined') { 
      result.push(rowIdName); 
     } 
     } 
     $(row).children('td,th').each(function(cellIndex, cell) { 
     result.push(cellValues(cellIndex, cell, isHeader)); 
     }); 
     return result; 
    }; 

    var getHeadings = function(table) { 
     var firstRow = table.find('tr:first').first(); 
     return notNull(opts.headings) ? opts.headings : rowValues(firstRow, true); 
    }; 

    var construct = function(table, headings) { 
     var i, j, len, len2, txt, $row, $cell, 
     tmpArray = [], cellIndex = 0, result = []; 
     table.children('tbody,*').children('tr').each(function(rowIndex, row) { 
     if(rowIndex > 0 || notNull(opts.headings)) { 
      var includeRowId = opts.includeRowId; 
      var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false; 

      $row = $(row); 

      var isEmpty = ($row.find('td').length === $row.find('td:empty').length) ? true : false; 

      if(($row.is(':visible') || !opts.ignoreHiddenRows) && (!isEmpty || !opts.ignoreEmptyRows) && (!$row.data('ignore') || $row.data('ignore') === 'false')) { 
      cellIndex = 0; 
      if (!tmpArray[rowIndex]) { 
       tmpArray[rowIndex] = []; 
      } 
      if (useRowId) { 
       cellIndex = cellIndex + 1; 
       if (typeof $row.attr('id') !== 'undefined') { 
       tmpArray[rowIndex].push($row.attr('id')); 
       } else { 
       tmpArray[rowIndex].push(''); 
       } 
      } 

      $row.children().each(function(){ 
       $cell = $(this); 
       // skip column if already defined 
       while (tmpArray[rowIndex][cellIndex]) { cellIndex++; } 

       // process rowspans 
       if ($cell.filter('[rowspan]').length) { 
       len = parseInt($cell.attr('rowspan'), 10) - 1; 
       txt = cellValues(cellIndex, $cell); 
       for (i = 1; i <= len; i++) { 
        if (!tmpArray[rowIndex + i]) { tmpArray[rowIndex + i] = []; } 
        tmpArray[rowIndex + i][cellIndex] = txt; 
       } 
       } 
       // process colspans 
       if ($cell.filter('[colspan]').length) { 
       len = parseInt($cell.attr('colspan'), 10) - 1; 
       txt = cellValues(cellIndex, $cell); 
       for (i = 1; i <= len; i++) { 
        // cell has both col and row spans 
        if ($cell.filter('[rowspan]').length) { 
        len2 = parseInt($cell.attr('rowspan'), 10); 
        for (j = 0; j < len2; j++) { 
         tmpArray[rowIndex + j][cellIndex + i] = txt; 
        } 
        } else { 
        tmpArray[rowIndex][cellIndex + i] = txt; 
        } 
       } 
       } 

       txt = tmpArray[rowIndex][cellIndex] || cellValues(cellIndex, $cell); 
       if (notNull(txt)) { 
       tmpArray[rowIndex][cellIndex] = txt; 
       } 
       cellIndex++; 
      }); 
      } 
     } 
     }); 
     $.each(tmpArray, function(i, row){ 
     if (notNull(row)) { 
      // remove ignoredColumns/add onlyColumns 
      var newRow = notNull(opts.onlyColumns) || opts.ignoreColumns.length ? 
      $.grep(row, function(v, index){ return !ignoredColumn(index); }) : row, 

      // remove ignoredColumns/add onlyColumns if headings is not defined 
      newHeadings = notNull(opts.headings) ? headings : 
       $.grep(headings, function(v, index){ return !ignoredColumn(index); }); 

      txt = arraysToHash(newHeadings, newRow); 
      result[result.length] = txt; 
     } 
     }); 
     return result; 
    }; 

    // Run 
    var headings = getHeadings(this); 
    return construct(this, headings); 
    }; 
})(jQuery); 

我可能失去了一些東西很簡單,但真的不能看到如何做到這一點。任何幫助將超級讚賞。謝謝大家!

+0

你jsons無效。逗號分隔的對象列表(數組)在方括號('{「data」:[{..},{..}')中定義。 –

+0

從假我只是跑遺憾的實際輸出爲 [{「時間」:「上午6:30 - 8:30」,「星期一」:「」,「星期二」:「」,「星期三」:「」 「星期四」: 「」, 「星期五」: 「」},{ 「時代」: 「11:15 AM - 12:45 PM」, 「星期一」: 「sdfsdfsdf」, 「星期二」: 「」, 「星期三」: 「」,「星期四」:「」,「星期五」:「」},{「時間」:「下午3:00 - 下午5:00」,「星期一」:「」,「星期二」 :「」,「星期四」:「」,「星期五」:「」},{「時間」:「下午5:00 - 晚上7:00」,「星期一」:「」,「星期二」:「」,星期二「:」「,」星期五「:」「,」「時間」:「晚上7點至晚上9點」,「星期一」:「」,「星期二」:「」,週三「:」」,‘星期四’:‘’,‘星期五’:‘’}] – UpSideDownJason

+0

很抱歉..這是我的剪切和粘貼失敗 – UpSideDownJason

回答

0

重新思考爲什麼你需要去改變它。這已經提供了有效的(通過foo.data[0]foo.data[1]等,或與可迭代訪問for(var i; i<foo.data.length;i++){})下令在JSON數組內容。

你想要的東西會給你一些沒有保證的順序(在一個對象中的屬性順序是不相關的在JSON中)並違背流程)。


編輯:愚蠢的API

如果你必須符合一些模糊和邪惡的標準,編輯它創建後的數據。你不能指望$.fn.tableToJSON不符合JSON & JavaScript的標準......

var foo = // output from $.fn.tableToJSON 
var out = {data:{}}; //declare an *object* instead of an array 
for(var i = 0; i < foo.data.length; i++){ 
    out.data['Session ' + (i + 1)] = foo.data[i]; 
} 
//debug output 
console.log(JSON.stringify(out)) 
+0

我同意你的意見。不幸的是,我正在把JSON放到需要這個端點的端點上,我想你可以稱它爲「id」或「name」? – UpSideDownJason

+1

這就是我想我不得不去做的事情。讓我測試並回復你。感謝您的幫助。超級讚賞 – UpSideDownJason

+0

熱潮!這是一種享受,api喜歡它。謝謝你,朋友! – UpSideDownJason