【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}]
相关推荐
橙露8 分钟前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化
Omigeq15 分钟前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
2301_8084143816 分钟前
自动化测试的实施
开发语言·python
小李子呢021120 分钟前
前端八股Vue(6)---v-if和v-for
前端·javascript·vue.js
程序员buddha23 分钟前
ES6 迭代器与生成器
前端·javascript·es6
波波00733 分钟前
写出稳定C#系统的关键:不可变性思想解析
开发语言·c#·wpf
aq553560036 分钟前
网页开发四剑客:HTML/CSS/JS/PHP全解析
javascript·css·html
程序员buddha44 分钟前
TypeScript详细教程
javascript·ubuntu·typescript
dr_yingli1 小时前
fMRI(3-1)报告(个体化报告)生成器说明
开发语言·matlab
hrhcode1 小时前
【java工程师快速上手go】一.Go语言基础
java·开发语言·golang