Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  40] [ 7]  / answers: 1 / hits: 16684  / 8 Years ago, mon, august 8, 2016, 12:00:00

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


More From » json

 Answers
18

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.


[#61100] Friday, August 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;