forked from afshinm/Json-to-HTML-Table
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-to-table.js
More file actions
executable file
·237 lines (210 loc) · 8.45 KB
/
json-to-table.js
File metadata and controls
executable file
·237 lines (210 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* JavaScript format string function
*
*/
String.prototype.format = function()
{
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number)
{
return typeof args[number] != 'undefined' ? args[number] :
'{' + number + '}';
});
};
/**
* Check if object exists in array
*/
function containsObject(obj, list) {
if (!list) return false;
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}
return false;
}
/**
* Get header name
*/
function getHeaderName(obj, headerNameMap) {
if (!headerNameMap) return false;
if (headerNameMap.hasOwnProperty(obj)) {
return headerNameMap[obj];
}
return obj;
}
/**
* Convert a Javascript Oject array or String array to an HTML table
* JSON parsing has to be made before function call
* It allows use of other JSON parsing methods like jQuery.parseJSON
* http(s)://, ftp://, file:// and javascript:; links are automatically computed
*
* JSON data samples that should be parsed and then can be converted to an HTML table
* var objectArray = '[{"tot":"34","ver":"1.0.4","off":"New York","pic":"https://en.wikipedia.org/wiki/New_York_City#/media/File:NYC_Montage_2014_4_-_Jleon.jpg"},{"tot":"67","ver":"1.1.0","off":"Paris","pic":"https://en.wikipedia.org/wiki/Paris#/media/File:Seine_and_Eiffel_Tower_from_Tour_Saint_Jacques_2013-08.JPG"}]';
* var imageColumns = ["pic"];
* var columnNames = {tot: "Total", ver: "Version", off: "Office", pic: "Photo"];
* var stringArray = '["New York","Berlin","Paris","Marrakech","Moscow"]';
* var nestedTable = '[{ key1: "val1", key2: "val2", key3: { tableId: "tblIdNested1", tableClassName: "clsNested", linkText: "Download", data: [{ subkey1: "subval1", subkey2: "subval2", subkey3: "subval3" }] } }]';
*
* Code sample to create a HTML table Javascript String
* var jsonHtmlTable = ConvertJsonToTable(eval(dataString), 'jsonTable', null, 'Download', imageColumns, columnNames);
*
* Code sample explaned
* - eval is used to parse a JSON dataString
* - table HTML id attribute will be 'jsonTable'
* - table HTML class attribute will not be added
* - 'Download' text will be displayed instead of the link itself
* - imageColumns array defines which headers contain image URLs
* - columnNames array defines what names should show in the HTML header
*
* @author Afshin Mehrabani <afshin dot meh at gmail dot com>
*
* @class ConvertJsonToTable
*
* @method ConvertJsonToTable
*
* @param parsedJson object Parsed JSON data
* @param tableId string Optional table id
* @param tableClassName string Optional table css class name
* @param linkText string Optional text replacement for link pattern
* @param imgHeaders array Optional defines which headers contain image URLs
* @param headerNames array Optional defines what names should show in the HTML headers
*
* @return string Converted JSON to HTML table
*/
function ConvertJsonToTable(parsedJson, tableId, tableClassName, linkText, imgHeaders, headerNames)
{
//Patterns for links and NULL value
var italic = '<i>{0}</i>';
var link = linkText ? '<a href="{0}">' + linkText + '</a>' :
'<a href="{0}">{0}</a>';
var image = '<a href="{0}" target="_blank"><img src="{0}" alt="Photo"></img></a>';
//Pattern for table
var idMarkup = tableId ? ' id="' + tableId + '"' :
'';
var classMarkup = tableClassName ? ' class="' + tableClassName + '"' :
'';
var tbl = '<table border="1" cellpadding="1" cellspacing="1"' + idMarkup + classMarkup + '>{0}{1}</table>';
//Patterns for table content
var th = '<thead>{0}</thead>';
var tb = '<tbody>{0}</tbody>';
var tr = '<tr>{0}</tr>';
var thRow = '<th>{0}</th>';
var tdRow = '<td>{0}</td>';
var thCon = '';
var tbCon = '';
var trCon = '';
if (parsedJson)
{
var isStringArray = typeof(parsedJson[0]) == 'string';
var headers;
// Create table headers from JSON data
// If JSON data is a simple string array we create a single table header
if(isStringArray)
thCon += thRow.format('value');
else
{
// If JSON data is an object array, headers are automatically computed
if(typeof(parsedJson[0]) == 'object')
{
headers = array_keys(parsedJson[0]);
for (i = 0; i < headers.length; i++) {
headerName = getHeaderName(headers[i], headerNames);
thCon += thRow.format(headerName);
}
}
}
th = th.format(tr.format(thCon));
// Create table rows from Json data
if(isStringArray)
{
for (i = 0; i < parsedJson.length; i++)
{
tbCon += tdRow.format(parsedJson[i]);
trCon += tr.format(tbCon);
tbCon = '';
}
}
else
{
if(headers)
{
var urlRegExp = new RegExp(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig);
var javascriptRegExp = new RegExp(/(^javascript:[\s\S]*;$)/ig);
for (i = 0; i < parsedJson.length; i++)
{
for (j = 0; j < headers.length; j++)
{
var value = parsedJson[i][headers[j]];
var isUrl = urlRegExp.test(value) || javascriptRegExp.test(value);
if(isUrl) { // If value is URL we auto-create a link
if (containsObject(headers[j], imgHeaders)) {
tbCon += tdRow.format(image.format(value));
} else {
tbCon += tdRow.format(link.format(value));
}
}
else
{
if(value){
if(typeof(value) == 'object'){
//for supporting nested tables
tbCon += tdRow.format(ConvertJsonToTable(eval(value.data), value.tableId, value.tableClassName, value.linkText, imgHeaders, null));
} else {
tbCon += tdRow.format(value);
}
} else { // If value == null we format it like PhpMyAdmin NULL values
tbCon += tdRow.format(italic.format(value).toUpperCase());
}
}
}
trCon += tr.format(tbCon);
tbCon = '';
}
}
}
tb = tb.format(trCon);
tbl = tbl.format(th, tb);
return tbl;
}
return null;
}
/**
* Return just the keys from the input array, optionally only for the specified search_value
* version: 1109.2015
* discuss at: http://phpjs.org/functions/array_keys
* + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* + input by: Brett Zamir (http://brett-zamir.me)
* + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* + improved by: jd
* + improved by: Brett Zamir (http://brett-zamir.me)
* + input by: P
* + bugfixed by: Brett Zamir (http://brett-zamir.me)
* * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
* * returns 1: {0: 'firstname', 1: 'surname'}
*/
function array_keys(input, search_value, argStrict)
{
var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = '';
if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return input.keys(search_value, argStrict);
}
for (key in input)
{
if (input.hasOwnProperty(key))
{
include = true;
if (search)
{
if (strict && input[key] !== search_value)
include = false;
else if (input[key] != search_value)
include = false;
}
if (include)
tmp_arr[tmp_arr.length] = key;
}
}
return tmp_arr;
}