【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}]
相关推荐
杜子不疼.2 小时前
【C++ AI 大模型接入 SDK】 - DeepSeek 模型接入(上)
开发语言·c++·chatgpt
加号32 小时前
【C#】 串口通信技术深度解析及实现
开发语言·c#
sycmancia2 小时前
Qt——编辑交互功能的实现
开发语言·qt
石山代码3 小时前
C++ 内存分区 堆区
java·开发语言·c++
无风听海3 小时前
C# 隐式转换深度解析
java·开发语言·c#
放下华子我只抽RuiKe54 小时前
React 从入门到生产(四):自定义 Hook
前端·javascript·人工智能·深度学习·react.js·自然语言处理·前端框架
一只大袋鼠4 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
LuminousCPP4 小时前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习
XinZong5 小时前
OpenClaw 实现双重心跳(Heartbeat)+ clawreach虾聊项目实现
javascript
web3.08889995 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python