我在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()但是没有预期的结果。
谢谢, 内甚
答案 0 :(得分:0)
假设服务器的响应始终采用您提供的格式,您可以像这样创建所需的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' } ] }