【JS】转换多个json结构的字符串为数组

文章目录

背景:今天遇到接口返回的 EventStream 结构的数据,由于http 流式传输时,可能会分段,所以导致本该每次返回一段json数据结构的字符串,变成了多个json数据结构的字符串拼接在了一起。

  • 例如:
js 复制代码
'{a: 1}{a: 2}{a: 3}'
  • 现在想要得到这种的:
js 复制代码
[{a: 1}, {a: 2}, {a: 3}]
  • 函数实现:支持深层嵌套的json结构
js 复制代码
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;
}
  • 效果:
js 复制代码
const arr = parseMultiJson('{a: 1}{a: 2}{a: 3}')
console.log(arr)	// [{a: 1}, {a: 2}, {a: 3}]
相关推荐
这儿有一堆花31 分钟前
python视觉开发
开发语言·python
半桶水专家1 小时前
ES Module 原理详解
前端·javascript
冴羽1 小时前
Cloudflare 崩溃梗图
前端·javascript·vue.js
Jonathan Star1 小时前
JavaScript 中,原型链的**最顶端(终极原型)只有一个——`Object.prototype`
开发语言·javascript·原型模式
普通网友1 小时前
C++中的组合模式
开发语言·c++·算法
q***61501 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php
Dneccc2 小时前
Qt5配置MSVC2017
开发语言·qt
江公望2 小时前
Qt QByteArray类型,10分钟讲清楚
开发语言·c++·qt
小灰灰搞电子2 小时前
Qt Sensors 传感器框架详解
开发语言·qt
LNN20222 小时前
Qt 5.8 中的 Qt Test:轻松实现自动化测试
开发语言·qt