将嵌套字符串转换为JSON对象javascript

时间:2015-12-23 07:30:22

标签: javascript json

我有一个嵌套查询字符串,如

var str = "( ( Sentence starts with any of null AND Sentence starts with any of null ) AND Sentence starts with any of null )"

如何通过使用javascript从AND运算符拆分为JSON对象来转换它,它应该如下所示:

{  
   "group":{  
      "operator":"AND",
      "rules":[  
         {  
            "group":{  
               "operator":"AND",
               "rules":[  
                  object1‌​,
                  object2
               ]
            }
         },
         object3
      ]
   }
}

1 个答案:

答案 0 :(得分:1)

在一般意义上,直到您的答案被清理为止:

var string = "my cool string AND I love JS AND isn't this cool?";

var operations = string.split(' AND '); // Gives an array: ["my cool string", "I love JS", "isn't this cool?"]

var group = {};

for(var i = 0; i < operations.length; ++i) {
  operations['operator' + i] = operations[i];
}

console.log(group); // { operator1: "my cool string", operator2: "I love JS", operator3: "isn't this cool?"}
console.log(JSON.stringify(group)); // gives JSON string representation of group