Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 209
user310291 Avatar asked Oct 22 '25 06:10

user310291


1 Answers

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.

like image 56
Arnauld Avatar answered Oct 23 '25 21:10

Arnauld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!