如何在javascript / nodejs中拆分包含n个连接json字符串的字符串?

时间:2016-08-08 15:22:17

标签: javascript json node.js

假设我从套接字服务器(我无法控制)收到此字符串:

{"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} 

我不能使用JSON.parse,因为它包含2个Json字符串,所以我怎么能分成

var jsonString1 = {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}

var jsonString2 = {"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} 

注意:我实际上可能有1到n个Json字符串连接

3 个答案:

答案 0 :(得分:6)

你可以这样做:

var data = '{"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}}';

var sanitized = '[' + data.replace(/}{/g, '},{') + ']';
var res = JSON.parse(sanitized);

console.log(res);

但是,如果其中一个对象在字符串中包含}{模式,则会失败。

答案 1 :(得分:3)

您可以按}出现后将其拆分,然后直接跟{(忽略空格)。

var parts = str.split(/\}\s*\{/g);
for(var i = 0; i < parts.length; i++) {
  var part = parts[i].trim();

  if(part[0] !== '{') part = '{' + part;
  if(part[part.length-1] !== '}') part += '}';

  var json = JSON.parse(part);
}

答案 2 :(得分:1)

只需在/\}\s*\{/g时拆分并传递值以填充Array.prototype.reduce函数。

&#13;
&#13;
var str = '{"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}}'

var data = (function(input) {
  let odd = true;
  
  return input.split(/\}\s*\{/g).reduce(function(res, part, i) {
    if(odd) {
      part += "}";
    } else {
      part = "{" + part;
    }
    
    odd = !odd;
    
    res[i] = JSON.parse(part);
    
    return res;
  }, {});
})(str)

console.log("data:", data);
&#13;
&#13;
&#13;