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

convert a nested string into JSON object javascript

本文关键字:JSON 对象 javascript 转换 嵌套 字符串      更新时间:2023-09-26

我有一个类似的嵌套查询字符串

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
      ]
   }
}

在一般意义上,直到你的答案被清除:

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