如何在JavaScript

时间:2018-06-04 05:13:59

标签: javascript jquery html json

如何在Javascript中将纯文本转换为JSON值。我尝试了很多。但无法按预期获取。请任何人帮忙

从命令行获取实际字符串,该命令行是从javascript执行命令

Net State: OFFLINE
Net Err:
Net Time: 0

Current Sample: 0

Sample #0
        Sample Role: OFFLINE
        Sample Status: DISABLED
        Sample Errors: ERROR STATUS
        Test Mode: FAILED
        Test Status: NOT RUNNING      

Sample #1
        Sample Role: ONLINE
        Sample Status: ENABLED
        Sample Errors: NO ERROR
        Test Mode: ENABLED
        Test Status: RUNNING

预期的JSON值

{
  "Net_State": "OFFLINE",
  "Net_Err": "",
  "Net_Time": 0,
  "Current_sample": 0,
  "Sample": [
        {
      "Sample_Role": "OFFLINE",
      "Sample_Status": "DISABLED",
      "Sample_Errors": "ERROR STATUS",
      "Test_Mode": "FAILED",
      "Test_Status": "NOT RUNNING"
    },
    {
      "Sample_Role": "ONLINE",
      "Sample_Status": "ENABLED",
      "Sample_Errors": "NO ERROR",
      "Test_Mode": "ENABLED",
      "Test_Status": "RUNNING"
    }
  ]
}

我尝试了下面的代码,但我怎么能写不久

var res = response.split(/\r?\n/);
res = res.filter(function(e){return e});
var myObject = {
node : []
};
var nodeObject =[];
var i =0, j=0, k = 0, l=0;
var sampleArr = []
var loop = false;
for (var i = 0; i < res.length; i++) {
var itemValue = res[i]
if (itemValue.includes(':')) {
        var sp = itemValue.split(':');
        if (!loop) {
        myObject[sp.shift().trim()] = sp.join(':').trim();
    } else {
        if(nodeObject.length > 0) {
            if (j ==0) {
                myObject.node[l] = nodeObject;
                nodeObject = [];
                l = l+1;
            }
        }

        nodeObject.push({[sp.shift().trim()] : sp.join(':').trim()});
        j = j+1;
        if (k > 0 && k == j) {
        myObject.node[l] = nodeObject;
        nodeObject = [];
        }
    }
} else {
    loop = true;
    k=j;        
    j = 0;
}
}     

提前致谢。

1 个答案:

答案 0 :(得分:3)

注意:我发布此代码时您没有发布任何代码,因此我仍然希望看到您出错的地方以帮助您理解

好的,你的代码有问题(唯一的问题?)是

nodeObject.push({[sp.shift().trim()] : sp.join(':').trim()});

这就是为什么Sample数组中的每个项目都是一个对象数组

尝试解决这个问题,但无论如何,下面的代码更好(如果我自己这么说的话)

&#13;
&#13;
const response = `Net State: OFFLINE
Net Err:
Net Time: 0

Current Sample: 0

Sample #0
        Sample Role: OFFLINE
        Sample Status: DISABLED
        Sample Errors: ERROR STATUS
        Test Mode: FAILED
        Test Status: NOT RUNNING      

Sample #1
        Sample Role: ONLINE
        Sample Status: ENABLED
        Sample Errors: NO ERROR
        Test Mode: ENABLED
        Test Status: RUNNING`;
        
let res = response.split(/\r?\n/g).filter(line => line.trim());
let curr = null;
const result = res.reduce((acc, line) => {
    if (/\s#\d+/.test(line)) { // array entry
        let [key, index] = line.split(' #');
        key = key.trim();
        index = +index;
        curr = {key, index}; // save the key and index
        let a = acc[key] = acc[key] || []; // initialise the array if needed
        a[index] = a[index] || {}; // initialise the object at the given index
    } else {
        let [key, ...value] = line.split(':');
        value = value.join(':').trim();
        if (key.startsWith(' ')) { // array
            acc[curr.key][curr.index][key.trim()] = value;
        } else { // root
            acc[key.trim()] = value;
        }
    }
    return acc;
}, {});
console.log(JSON.stringify(result, null, 4));
&#13;
&#13;
&#13;