通过JQuery将字符串转换为JSON

Convert String into JSON through JQuery

本文关键字:JSON 转换 字符串 JQuery 通过      更新时间:2023-09-26

字符串为:

AVG(Disk Usage,CPU USAGE,NETWORK USAGE,SUM(Shared Memory Usage,System Memory Usage))

所需输出:

{
   "operation": "AVG",
   "rules": [
     {
       "field": "Disk Usage"
     },
     {
       "field": "CPU Usage"
     },
     {
       "field": "Network Usage"
     },
     {
       "operation": "SUM",
       "rules": [
         {
           "field": "Shared Memory Usage"
         },
         {
           "field": "System Memory Usage"
         }
       ]
     }
  ]
}

我已经使用一些正则表达式模式RegExp.execString.splitArray.map函数为您的案例编写了解决方案
我还添加了一个嵌套运算符来处理复杂的示例
希望它能有所帮助。。。

var str = "AVG(Disk Usage,CPU USAGE,NETWORK USAGE,SUM(Shared Memory Usage,System Memory Usage),COUNT(Processes,Services))",
    re = /('w+?)'(([^()]+)(?=,'w+?'()|(?:,'))?('w+?)'(([^)]+)/g, m, idx, 
    obj = {}, result = {};
while ((m = re.exec(str)) !== null) {
    idx = m.index;  // position of the current matched item in the initial input string
    m = m.filter((v) => v); // to get consecutive filled matched items
    obj = {'operation': m[1], 'rules' : m[2].split(",").map((v) => ({'field':v}))};
    if (idx === 0) { // the first function(operator) i.e. "AVG"
        result = obj;
    } else {
        result['rules'].push(obj);
    }
}
console.log(JSON.stringify(result, 0, 4));

输出:

{
    "operation": "AVG",
    "rules": [
        {
            "field": "Disk Usage"
        },
        {
            "field": "CPU USAGE"
        },
        {
            "field": "NETWORK USAGE"
        },
        {
            "operation": "SUM",
            "rules": [
                {
                    "field": "Shared Memory Usage"
                },
                {
                    "field": "System Memory Usage"
                }
            ]
        },
        {
            "operation": "COUNT",
            "rules": [
                {
                    "field": "Processes"
                },
                {
                    "field": "Services"
                }
            ]
        }
    ]
}

试试看:

JSON.parse(jsonObj); //javascript

你应该这样做:

var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);

希望它能有所帮助;)