-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
78 lines (68 loc) · 1.93 KB
/
index.js
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
/*
change for npm modules.
by Luiz Estácio.
json-format v.1.1
http://github.com/phoboslab/json-format
Released under MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
var p = [],
indentConfig = {
tab: { char: '\t', size: 1 },
space: { char: ' ', size: 4 }
},
configDefault = {
type: 'tab'
},
push = function( m ) { return '\\' + p.push( m ) + '\\'; },
pop = function( m, i ) { return p[i-1] },
tabs = function( count, indentType) { return new Array( count + 1 ).join( indentType ); };
function JSONFormat ( json, indentType ) {
p = [];
var out = "",
indent = 0;
// Extract backslashes and strings
json = json
.replace( /\\./g, push )
.replace( /(".*?"|'.*?')/g, push )
.replace( /\s+/, '' );
// Indent and insert newlines
for( var i = 0; i < json.length; i++ ) {
var c = json.charAt(i);
switch(c) {
case '{':
case '[':
out += c + "\n" + tabs(++indent, indentType);
break;
case '}':
case ']':
out += "\n" + tabs(--indent, indentType) + c;
break;
case ',':
out += ",\n" + tabs(indent, indentType);
break;
case ':':
out += ": ";
break;
default:
out += c;
break;
}
}
// Strip whitespace from numeric arrays and put backslashes
// and strings back in
out = out
.replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } )
.replace( /\\(\d+)\\/g, pop ) // strings
.replace( /\\(\d+)\\/g, pop ); // backslashes in strings
return out;
};
module.exports = function(json, config){
config = config || configDefault;
var indent = indentConfig[config.type];
if ( indent == null ) {
throw new Error('Unrecognized indent type: "' + config.type + '"');
}
var indentType = new Array((config.size || indent.size) + 1).join(indent.char);
return JSONFormat(JSON.stringify(json), indentType);
}