2017-12-17
JSON
JSON String Parse
JavaScript 实现 JSON 字符串格式化:
00const strParse = require('./str-parse')
01    , str = `{"b":{"c":{"d":{"k":"asd"}},"e":{"f":{"j":"j"}}},"gg":{"ff":"123"},"abc":{"yu":{"l":"lolo"}}}`
02
03// test 
04let str_formatted = strParse(str); 
05
06console.log(str_formatted);
07console.log(str);
Like This:
00# From This 
01{"b":{"c":{"d":{"k":"asd"}},"e":{"f":{"j":"j"}}},"gg":{"ff":"123"},"abc":{"yu":{"l":"lolo"}}}
02
03# To This 
04{
05    "b": {
06        "c": {
07            "d": {
08                "k": "asd"
09            }
10        },
11        "e": {
12            "f": {
13                "j": "j"
14            }
15        }
16    },
17    "gg": {
18        "ff": "123"
19    },
20    "abc": {
21        "yu": {
22            "l": "lolo"
23        }
24    }
25}

# str-parse.js

00// To Generate Tab (in 4 spaces)
01var nTab = n => '    '.repeat(n); 
02
03// Token Process Table 
04let tokenTable = {
05    '{': (x, deep, next) => x + '\n' + nTab(deep) + next(),
06    '}': (x, deep, next) => '\n' + nTab(deep) + x + next(),
07    ',': (x, deep, next) => x + '\n' + nTab(deep) + next(), 
08    ':': (x, deep, next) => x + ' ' + next(), 
09    'default': (x, deep, next) => x + next(),
10    get: function(key){
11        return this[key] || this['default']
12    }
13}
14
15// Deep Process Table
16let deepTable = {
17    '{': d => d + 1, 
18    '}': d => d - 1, 
19    'default': d => d,
20    get: function(key){
21        return this[key] || this['default']
22    }
23}
24
25/**
26 * @description JSON 字符数组格式化
27 * @param {Array<String>} chars 
28 * @param {Number} deep 
29 */
30function _parse(chars, deep = 0){
31    let [x, ...xs] = chars; 
32
33    if (!x) return ''; 
34
35    let tokenProcess = tokenTable.get(x)
36    // tokenTable[x] || tokenTable['default']; 
37    let deepProcess = deepTable.get(x); 
38
39    // Process 
40    deep = deepProcess(deep); 
41
42    return tokenProcess(x, deep, () => {
43        return _parse(xs, deep); 
44    }); 
45}
46
47/**
48 * @description 正式进行格式化之前的预处理 (把字符串字符数组)
49 * @param {String} s 
50 */
51var parse = s => _parse(
52    s.split('')
53); 
54
55parse.deepTable = deepTable; 
56parse.tokenProcess = tokenTable; 
57
58module.exports = parse;

# More

有空写一篇 JSON.parse && JSON.stringify 的 Polyfill




回到顶部