假设我从套接字服务器(我无法控制)收到此字符串:
{"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字符串连接
答案 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
函数。
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;