简体   繁体   English

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

[英]convert a nested string into JSON object javascript

I have a nested query String like我有一个嵌套的查询字符串,例如

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

How do I convert it by splitting from AND operator into a JSON object using javascript which should look like:如何通过使用 javascript 将 AND 运算符拆分为 JSON 对象来将其转换为如下所示:

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

In the general sense until your answer is cleaned up:一般来说,直到你的答案被清理干净:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM