2 * Author: Alex Kocharin <alex@kocharin.ru>
3 * GIT: https://github.com/rlidwka/jju
4 * License: WTFPL, grab your copy here: http://www.wtfpl.net/txt/copying/
7 var tokenize = require('./parse').tokenize
9 module.exports.analyze = function analyzeJSON(input, options) {
10 if (options == null) options = {}
12 if (!Array.isArray(input)) {
13 input = tokenize(input, options)
17 has_whitespace: false,
20 has_trailing_comma: false,
33 for (var i=0; i<input.length; i++) {
34 if (input[i].type === 'newline') {
35 if (input[i+1] && input[i+1].type === 'whitespace') {
36 if (input[i+1].raw[0] === '\t') {
37 // if first is tab, then indent is tab
38 stats.indent['\t'] = (stats.indent['\t'] || 0) + 1
40 if (input[i+1].raw.match(/^\x20+$/)) {
41 // if all are spaces, then indent is space
42 // this can fail with mixed indent (4, 2 would display 3)
43 var ws_len = input[i+1].raw.length
44 var indent_len = input[i+1].stack.length + 1
45 if (ws_len % indent_len === 0) {
46 var t = Array(ws_len / indent_len + 1).join(' ')
47 stats.indent[t] = (stats.indent[t] || 0) + 1
52 stats.newline[input[i].raw] = (stats.newline[input[i].raw] || 0) + 1
55 if (input[i].type === 'newline') {
56 result.has_newlines = true
58 if (input[i].type === 'whitespace') {
59 result.has_whitespace = true
61 if (input[i].type === 'comment') {
62 result.has_comments = true
64 if (input[i].type === 'key') {
65 if (input[i].raw[0] !== '"' && input[i].raw[0] !== "'") result.quote_keys = false
68 if (input[i].type === 'key' || input[i].type === 'literal') {
69 if (input[i].raw[0] === '"' || input[i].raw[0] === "'") {
70 stats.quote[input[i].raw[0]] = (stats.quote[input[i].raw[0]] || 0) + 1
74 if (input[i].type === 'separator' && input[i].raw === ',') {
75 for (var j=i+1; j<input.length; j++) {
76 if (input[j].type === 'literal' || input[j].type === 'key') break
77 if (input[j].type === 'separator') result.has_trailing_comma = true
82 for (var k in stats) {
83 if (Object.keys(stats[k]).length) {
84 result[k] = Object.keys(stats[k]).reduce(function(a, b) {
85 return stats[k][a] > stats[k][b] ? a : b