Javascript解析字符串并构建json树

时间:2019-02-21 17:08:11

标签: javascript recursion

我有一个带有一些标记的字符串作为文本块。每个块都有一个开始和结束,例如:

$FOO_B$  // FOO begin block
...      // FOO value
$FOO_E$  // FOO end block

这种块结构是嵌套的,例如:

$FOO_B$    // FOO begin block
  $BAR_B$  // BAR begin block
    TEST   // BAR value
  $BAR_E$  // BAR end block
$FOO_E$    // FOO end block

我想要从字符串中构建一个json,例如:

[
    {
        "key": "FOO",
        "value": null,
        "children": [
            {
                "key": "BAR",
                "value": "TEST",
                "children": []
            }
        ]
    }
]

我已经写了一个基本功能

// return the string between a "prefix" and a "suffix" in a "str"
function getStringBetween(str, prefix, suffix) {
  let i = str.indexOf(prefix);
  if (i >= 0) {
    str = str.substring(i + prefix.length);
  } else {
    return '';
  }
  if (suffix) {
    i = str.indexOf(suffix);
    if (i >= 0) {
      str = str.substring(0, i);
    } else {
      return '';
    }
  }
  return str;
}

function parseGroup(text) {
    text = text.trim();
    var vars = [];
    if ( text.startsWith('$') && text.endsWith('$') ){
        var regexGroup = /\$[A-Za-z0-9\_]+\_B\$/g;
        var matchGroup;
        do {
            matchGroup = regexGroup.exec(text);
            if (matchGroup) {
                var startGroupName = matchGroup[0];
                var endGroupName = startGroupName.replace('_B$', '_E$');
                var groupName = startGroupName.replace('_B$', '');
                groupName = groupName.substring(1);
                    
                var valueGroup = getStringBetween(text, startGroupName, endGroupName);
                valueGroup = valueGroup.trim();

                var childGroup = parseGroup(valueGroup);
                if ( childGroup.length > 0 ){
                    valueGroup = null;
                }
                    
                var result = {
                    key: groupName,
                    value: valueGroup,
                    children: childGroup,
                };
                vars.push(result);
            }
            } while (matchGroup);
        }
        return vars;
}

var STR = "$FOO_B$ $BAR_B$ TEST $BAR_E$ $FOO_E$";

var group = parseGroup(STR);
var appDiv = document.getElementById('app');
appDiv.innerHTML = JSON.stringify(group, null, 4);
Output:
<pre><code id="app"></code></pre>

Expected:
<pre><code>
[
    {
        "key": "FOO",
        "value": null,
        "children": [
            {
                "key": "BAR",
                "value": "TEST",
                "children": []
            }
        ]
    }
]
</code></pre>

实时演示:https://stackblitz.com/edit/typescript-tukxrg

我的递归是错误的,但是我不明白为什么...

0 个答案:

没有答案