user310291
user310291

Reputation: 38190

How can I split a string containing n concatenated json string in javascript/nodejs?

Let's say I receive this string from a socket server (which I cannot control):

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

I cannot use JSON.parse since it contains 2 Json string so how can I split into

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

and

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

Note: I may have 1 to n Json strings concatenated in fact

Upvotes: 4

Views: 20647

Answers (3)

Hitmands
Hitmands

Reputation: 14179

Just split when /\}\s*\{/g and pass a value to fill to the Array.prototype.reduce function.

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);

Upvotes: 1

Arnauld
Arnauld

Reputation: 6110

You could just do:

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);

However, this will fail if one of the objects contains the }{ pattern in a string.

Upvotes: 9

micah
micah

Reputation: 8096

You can split them by the occurrence of } followed directly by { (ignoring whitespace).

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);
}

Upvotes: 4

Related Questions