将常规字符串解析为 JSON in node.js

Parse a regular string to JSON in node.js

我在 node.js 中有以下字符串,我从服务器

{"response":"Name 1: local value1 remote value2  state ACTIVE\nName 2: local value3  remote value4  state ACTIVE"}

我想将其转换为 JSON 格式,如下所示 -

{  
                    "response":[
                        {
                            "Name":1,
                            "local":"value1",
                            "remote":"value2",
                            "state":"active"
                        },
                        {
                            "Name":2,
                            "local":"value3",
                            "remote":"value4",
                            "state":"active"
                        }
                    ]
                }

我不能使用JQuery,因为这是在服务器端。

我试过 JSON.parse() 但没有产生预期的结果。

谢谢, 象头神

假设服务器的响应总是以您提供的格式出现,您可以像这样创建您想要的 JSON:

var json = {"response":"Name 1: local value1 remote value2  state ACTIVE\nName 2: local value3  remote value4  state ACTIVE"};

function parse(json) {
  var responses = json.response.split("\n"),
      regex = /(([A-Za-z0-9]+) ([A-Za-z0-9]+))+/g,
      result = { response:[] };

  responses.forEach(function(res) {
    var match, resp = {};
    while(match = regex.exec(res))
      resp[match[2]] = match[3].toLowerCase();

    result.response.push(resp);
  });

  return result;
}

console.log(parse(json));
// =>
//{ response: 
//   [ { Name: '1', local: 'value1', remote: 'value2', state: 'active' },
//     { Name: '2', local: 'value3', remote: 'value4', state: 'active' } ] }