门户网站模板之家,免费域名注册二级域名,室内装饰设计师证书,wap视频网站建设难吗?文章目录 背景#xff1a;今天遇到接口返回的 EventStream 结构的数据#xff0c;由于http 流式传输时#xff0c;可能会分段#xff0c;所以导致本该每次返回一段json数据结构的字符串#xff0c;变成了多个json数据结构的字符串拼接在了一起。 例如#xff1a;
{a: 1}… 文章目录 背景今天遇到接口返回的 EventStream 结构的数据由于http 流式传输时可能会分段所以导致本该每次返回一段json数据结构的字符串变成了多个json数据结构的字符串拼接在了一起。 例如
{a: 1}{a: 2}{a: 3}现在想要得到这种的
[{a: 1}, {a: 2}, {a: 3}]函数实现支持深层嵌套的json结构
function parseMultiJson(jsonStr) {const jsonArr [];let startIndex 0;let endIndex 0;while (startIndex jsonStr.length) {// 找到一个 JSON 对象的开始位置startIndex jsonStr.indexOf({, startIndex);if (startIndex -1) {break;}// 找到一个 JSON 对象的结束位置let openBrackets 1;endIndex startIndex 1;while (openBrackets 0 endIndex jsonStr.length) {if (jsonStr[endIndex] {) {openBrackets;} else if (jsonStr[endIndex] }) {openBrackets--;}endIndex;}// 将该 JSON 对象解析为一个对象并添加到数组中const json jsonStr.substring(startIndex, endIndex);jsonArr.push(JSON.parse(json));// 更新下一个 JSON 对象的开始位置startIndex endIndex;}return jsonArr;
}效果
const arr parseMultiJson({a: 1}{a: 2}{a: 3})
console.log(arr) // [{a: 1}, {a: 2}, {a: 3}]