Javascript使用正则表达式和对象属性在嵌套对象中查找嵌套对象

时间:2017-05-09 15:24:57

标签: javascript regex

我正在将一个字符串转换为一个对象,然后循环遍历该对象。出于某种原因,如果字符串是半正确格式化的,并且我没有执行前两个步骤(用大括号替换括号),它可以正常工作。

然而,替换放置单个'而不是'(虽然它仍然没有错误地解析)。解析错过了将第二个id放在employeeType下面,并错误地将它放在员工之下。

https://codepen.io/MrMooCats/pen/zwpQGa

var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

str = str.replace(/[(]/g, "{"); // Possible problem line?
str = str.replace(/[)]/g, "}"); // Possible problem line?
str = str.replace(/([A-z])\s*{/g, "$1\":{");
str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
str = str.replace(/({)/g, "{\"");
str = str.replace(/(,)/g, ",\"");
var objectStr = JSON.parse(str); // Object created, but wrong


var objectOutput = function(obj, counter) {
    for(var i in obj) {
      console.log(Array(counter+1).join("-") + " " + i);
        if(obj.hasOwnProperty(i)){
          if (obj[i] != null) {
            objectOutput(obj[i], counter+1);
          } else {
            counter = 0;
          }
        }
    }
};

objectOutput(objectStr, 0);

实际输出:

" id"

" created"

" employee"

"- id"

" firstname"

" employeeType"

"- id"

" lastname"

" location"

预期产出

" id"

" created"

" employee"

"- id"

"- firstname"

"- lastname"

"- employeeType"

"-- id"

" location"

1 个答案:

答案 0 :(得分:1)

要获得所需的输出,您需要修复objectOutput功能:



    // Works fine if the ( are { instead and remove the first two lines
    var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

    str = str.replace(/[(]/g, "{"); // Possible problem line?
    str = str.replace(/[)]/g, "}"); // Possible problem line?
    str = str.replace(/([A-z])\s*{/g, "$1\":{");
    str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
    str = str.replace(/({)/g, "{\"");
    str = str.replace(/(,)/g, ",\"");
    var objectStr = JSON.parse(str); // Object created, but wrong


    var objectOutput = function(obj, counter) {
        for (var i in obj) {
            console.log(Array(counter + 1).join("-") + " " + i);
            if (obj.hasOwnProperty(i)) {
                if (obj[i] != null) {
                    objectOutput(obj[i], counter + 1);
                }
            }
        }
    };
    objectOutput(objectStr, 0);




我也会这样改变正则​​表达式:



    var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

    str = str.replace(/\(/g, "{").replace(/\)/g, "}");
    str = str.replace(/([_a-zA-Z][_a-zA-Z0-9]*)\s*([,{}])/g, function(m, name, x){
        return '"'+name+'":' + (x != '{' ? 'null' : '') + x;});
    var objectStr = JSON.parse(str);

    var objectOutput = function(obj, counter) {
        for (var i in obj) {
            console.log(Array(counter + 1).join("-") + " " + i);
            if (obj.hasOwnProperty(i)) {
                if (obj[i] != null) {
                    objectOutput(obj[i], counter + 1);
                }
            }
        }
    };
    objectOutput(objectStr, 0);