0

几天前,我发现了一种非常好的方法来将css-strings(甚至嵌套)解析为json. 但是,它似乎在某个地方存在一个大问题。

https://github.com/csvplot/cml-parse

如果我们尝试解析css-string,它会杀死浏览器窗口,不知道这里发生了什么......我已经打开了一个问题但没有人回答这个问题,因为维护者大卫埃利斯迷路了。

有什么想法/建议吗?

function parse(data) {
    var stateStack = [];
    var scopeStack = [];
    var outObj = {};

    while(data) {

        // Grab current number of indentation characters
        /^(\s*)/.test(data);
        // If we've entered any state, and that state is not an explicit block declaration ( {}'s ) and we have an indent level smaller than the most recent indent level,
        // then remove the most recent scope level and recall the state back to the previous scope's state
        if(stateStack.length &&
           stateStack[stateStack.length-1] !== 'explicitBlock' &&
           scopeStack.length &&
           RegExp.$1.length < scopeStack[scopeStack.length-1].indent) {
            scopeStack.pop();
            while(stateStack.length && (stateStack[stateStack.length-1] !== 'block' || stateStack[stateStack.length-1] !== 'explicitBlock')) {
                stateStack.pop();
            }
        }
        // If current chunk is the key to an object
        if(/^(\s*)([^:]*)\s*([{\n])/.test(data)) {
            // Grab the indent size of the key and the current outObj position from the scope stack
            var indentLength = RegExp.$1.length;
            var currScope = (scopeStack.length ? scopeStack[scopeStack.length-1].ref : outObj);
            // Split the identifier by spaces and construct/traverse down the defined path
            // TODO: Figure out how to handle commas that define the same inner content along multiple paths
            RegExp.$2.split(/\s*/).forEach(function(scope) {
                if(scope !== '') {
                    currScope[scope] = currScope[scope] || {};
                    currScope = currScope[scope];
                }
            });
            // Push the deepest scope and the current indent length onto the scope stack, and push the explicitBlock vs block state onto the state stack
            // TODO: Work on a state diagram to truly handle all of the possible states involved properly
            scopeStack.push({ref: currScope, indent: indentLength});
            stateStack.push(RegExp.$3 === '{' ? 'explicitBlock' : 'block');
            // Rip out the handled chunk of data from the string
            data = data.replace(/^\s*[^:]*\s*[{\n]/, '');
        }
    }
    return data;
}

http://fiddle.jshell.net/5pTBr/

4

1 回答 1

0

运行代码,看起来它只是不起作用。

由于此正则表达式在第一次运行后失败,因此它达到了无限循环:

if(/^(\s*)([^:]*)\s*([{\n])/.test(data)) {

因此,为什么浏览器卡住了。它也不会返回正确的 JSON。

我建议你自己写这样的东西,或者尝试调试和修复现有的代码。

于 2013-07-08T14:31:23.753 回答