├── .sourcedoc.yml ├── README.md └── json-to-table.js /.sourcedoc.yml: -------------------------------------------------------------------------------- 1 | engine: 2 | yuidoc 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Annoucement: We have developed a full-featured table library that supports JSON input as well. Please use [Grid.js](https://gridjs.io) instead. 2 | 3 | JSON to HTML Table 4 | ================== 5 | 6 | This is a simple script to convert JSON data to standard HTML table in the simplest and fastest way. 7 | 8 | ## How to use 9 | There's only one function in this library and accept four parameter that only the first one is required. 10 | 11 | ```javascript 12 | function ConvertJsonToTable(parsedJson, tableId, tableClassName, linkText) 13 | ``` 14 | 15 | Simply call `ConvertJsonToTable` method and fill the `parsedJson` parameter. 16 | 17 | ## Example 18 | 19 | This is an example of using this library: 20 | 21 | ```javascript 22 | //Example data, Object 23 | var objectArray = [{ 24 | "Total": "34", 25 | "Version": "1.0.4", 26 | "Office": "New York" 27 | }, { 28 | "Total": "67", 29 | "Version": "1.1.0", 30 | "Office": "Paris" 31 | }]; 32 | 33 | //Example data, Array 34 | var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"]; 35 | 36 | //Example data, nested Object. This data will create nested table also. 37 | var nestedTable = [{ 38 | key1: "val1", 39 | key2: "val2", 40 | key3: { 41 | tableId: "tblIdNested1", 42 | tableClassName: "clsNested", 43 | linkText: "Download", 44 | data: [{ 45 | subkey1: "subval1", 46 | subkey2: "subval2", 47 | subkey3: "subval3" 48 | }] 49 | } 50 | }]; 51 | ``` 52 | 53 | Code sample to create a HTML table from JSON: 54 | 55 | ```javascript 56 | //Only first parameter is required 57 | var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download'); 58 | ``` 59 | 60 | Code sample explaned: 61 | - First parameter is JSON data 62 | - table HTML id attribute will be **jsonTable** 63 | - table HTML class attribute will not be added 64 | - **Download** text will be displayed instead of the link itself 65 | 66 | ## Contributors 67 | [Afshin Mehrabani](https://github.com/afshinm) (@afshinmeh) 68 | [Sgissinger](https://github.com/sgissinger) 69 | 70 | ## Contributing 71 | 72 | This is a open-source project. Fork the project, complete the code and send pull request. 73 | 74 | ## License 75 | 76 | Copyright (C) 2012 Afshin Mehrabani (afshin.meh@gmail.com) 77 | 78 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 79 | documentation files (the "Software"), to deal in the Software without restriction, including without limitation 80 | the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 81 | and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 82 | The above copyright notice and this permission notice shall be included in all copies or substantial portions 83 | of the Software. 84 | 85 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 86 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 87 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 88 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 89 | IN THE SOFTWARE. 90 | 91 | -------------------------------------------------------------------------------- /json-to-table.js: -------------------------------------------------------------------------------- 1 | /** 2 | * JavaScript format string function 3 | * 4 | */ 5 | String.prototype.format = function() 6 | { 7 | var args = arguments; 8 | 9 | return this.replace(/{(\d+)}/g, function(match, number) 10 | { 11 | return typeof args[number] != 'undefined' ? args[number] : 12 | '{' + number + '}'; 13 | }); 14 | }; 15 | 16 | 17 | /** 18 | * Convert a Javascript Oject array or String array to an HTML table 19 | * JSON parsing has to be made before function call 20 | * It allows use of other JSON parsing methods like jQuery.parseJSON 21 | * http(s)://, ftp://, file:// and javascript:; links are automatically computed 22 | * 23 | * JSON data samples that should be parsed and then can be converted to an HTML table 24 | * var objectArray = '[{"Total":"34","Version":"1.0.4","Office":"New York"},{"Total":"67","Version":"1.1.0","Office":"Paris"}]'; 25 | * var stringArray = '["New York","Berlin","Paris","Marrakech","Moscow"]'; 26 | * var nestedTable = '[{ key1: "val1", key2: "val2", key3: { tableId: "tblIdNested1", tableClassName: "clsNested", linkText: "Download", data: [{ subkey1: "subval1", subkey2: "subval2", subkey3: "subval3" }] } }]'; 27 | * 28 | * Code sample to create a HTML table Javascript String 29 | * var jsonHtmlTable = ConvertJsonToTable(eval(dataString), 'jsonTable', null, 'Download'); 30 | * 31 | * Code sample explaned 32 | * - eval is used to parse a JSON dataString 33 | * - table HTML id attribute will be 'jsonTable' 34 | * - table HTML class attribute will not be added 35 | * - 'Download' text will be displayed instead of the link itself 36 | * 37 | * @author Afshin Mehrabani 38 | * 39 | * @class ConvertJsonToTable 40 | * 41 | * @method ConvertJsonToTable 42 | * 43 | * @param parsedJson object Parsed JSON data 44 | * @param tableId string Optional table id 45 | * @param tableClassName string Optional table css class name 46 | * @param linkText string Optional text replacement for link pattern 47 | * 48 | * @return string Converted JSON to HTML table 49 | */ 50 | function ConvertJsonToTable(parsedJson, tableId, tableClassName, linkText) 51 | { 52 | //Patterns for links and NULL value 53 | var italic = '{0}'; 54 | var link = linkText ? '' + linkText + '' : 55 | '{0}'; 56 | 57 | //Pattern for table 58 | var idMarkup = tableId ? ' id="' + tableId + '"' : 59 | ''; 60 | 61 | var classMarkup = tableClassName ? ' class="' + tableClassName + '"' : 62 | ''; 63 | 64 | var tbl = '{0}{1}
'; 65 | 66 | //Patterns for table content 67 | var th = '{0}'; 68 | var tb = '{0}'; 69 | var tr = '{0}'; 70 | var thRow = '{0}'; 71 | var tdRow = '{0}'; 72 | var thCon = ''; 73 | var tbCon = ''; 74 | var trCon = ''; 75 | 76 | if (parsedJson) 77 | { 78 | var isStringArray = typeof(parsedJson[0]) == 'string'; 79 | var headers; 80 | 81 | // Create table headers from JSON data 82 | // If JSON data is a simple string array we create a single table header 83 | if(isStringArray) 84 | thCon += thRow.format('value'); 85 | else 86 | { 87 | // If JSON data is an object array, headers are automatically computed 88 | if(typeof(parsedJson[0]) == 'object') 89 | { 90 | headers = array_keys(parsedJson[0]); 91 | 92 | for (var i = 0; i < headers.length; i++) 93 | thCon += thRow.format(headers[i]); 94 | } 95 | } 96 | th = th.format(tr.format(thCon)); 97 | 98 | // Create table rows from Json data 99 | if(isStringArray) 100 | { 101 | for (var i = 0; i < parsedJson.length; i++) 102 | { 103 | tbCon += tdRow.format(parsedJson[i]); 104 | trCon += tr.format(tbCon); 105 | tbCon = ''; 106 | } 107 | } 108 | else 109 | { 110 | if(headers) 111 | { 112 | var urlRegExp = new RegExp(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig); 113 | var javascriptRegExp = new RegExp(/(^javascript:[\s\S]*;$)/ig); 114 | 115 | for (var i = 0; i < parsedJson.length; i++) 116 | { 117 | for (var j = 0; j < headers.length; j++) 118 | { 119 | var value = parsedJson[i][headers[j]]; 120 | var isUrl = urlRegExp.test(value) || javascriptRegExp.test(value); 121 | 122 | if(isUrl) // If value is URL we auto-create a link 123 | tbCon += tdRow.format(link.format(value)); 124 | else 125 | { 126 | if(value){ 127 | if(typeof(value) == 'object'){ 128 | //for supporting nested tables 129 | tbCon += tdRow.format(ConvertJsonToTable(eval(value.data), value.tableId, value.tableClassName, value.linkText)); 130 | } else { 131 | tbCon += tdRow.format(value); 132 | } 133 | 134 | } else { // If value == null we format it like PhpMyAdmin NULL values 135 | tbCon += tdRow.format(italic.format(value).toUpperCase()); 136 | } 137 | } 138 | } 139 | trCon += tr.format(tbCon); 140 | tbCon = ''; 141 | } 142 | } 143 | } 144 | tb = tb.format(trCon); 145 | tbl = tbl.format(th, tb); 146 | 147 | return tbl; 148 | } 149 | return null; 150 | } 151 | 152 | 153 | /** 154 | * Return just the keys from the input array, optionally only for the specified search_value 155 | * version: 1109.2015 156 | * discuss at: http://phpjs.org/functions/array_keys 157 | * + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 158 | * + input by: Brett Zamir (http://brett-zamir.me) 159 | * + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 160 | * + improved by: jd 161 | * + improved by: Brett Zamir (http://brett-zamir.me) 162 | * + input by: P 163 | * + bugfixed by: Brett Zamir (http://brett-zamir.me) 164 | * * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} ); 165 | * * returns 1: {0: 'firstname', 1: 'surname'} 166 | */ 167 | function array_keys(input, search_value, argStrict) 168 | { 169 | var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = ''; 170 | 171 | if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array 172 | return input.keys(search_value, argStrict); 173 | } 174 | 175 | for (key in input) 176 | { 177 | if (input.hasOwnProperty(key)) 178 | { 179 | include = true; 180 | if (search) 181 | { 182 | if (strict && input[key] !== search_value) 183 | include = false; 184 | else if (input[key] != search_value) 185 | include = false; 186 | } 187 | if (include) 188 | tmp_arr[tmp_arr.length] = key; 189 | } 190 | } 191 | return tmp_arr; 192 | } 193 | --------------------------------------------------------------------------------