JavaScript解析拼接JSON字符串为数组的方法

作者:异步漫步时间:2026-10-31 15:28:26浏览:399

本文介绍在JavaScript中处理因HTTP流式传输导致多个JSON对象拼接成单一字符串的问题。通过自定义函数遍历字符串并提取完整JSON对象,将其解析为数组。同时对比eval与JSON.parse的使用场景,强调后者在性能与安全上的优势,并提供处理嵌套数组等复杂结构的示例。

接口返回的EventStream结构数据在HTTP流式传输过程中可能因分段导致原本每次返回的一段JSON字符串,变为多个JSON数据结构字符串拼接在一起的情况。本文旨在讲解在JavaScript中如何将这种由多个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}]

拓展

json字符串中只有一组

jsonstr = "{'name':'xiaoming','age':'11','lastTime':'2016-07-26','address':'luoyang'}";
jsonArray = eval(jsonstr);

json字符串中有多组

jsonstr2 = "[{'name':'xiaoming','age':'11','lastTime':'2016-07-26','address':'luoyang'},{'name':'xiaoming2','age':'12','lastTime':'2016-07-27','address':'luoyang2'}]";
jsonArray2= eval(jsonstr2);

json字符串中数组中嵌套的还有数组

jsonstr3 = "{'name':'xiaoming','age':'11','lastTime':'2016-07-26','address':{'pro':'henan','city':'luoy'}}";
jsonArray3 = eval('(' + jsonstr3 + ')');

JS中将object类型转换为json字符串

const obj = {name: "John", age: 30};
const jsonString = JSON.stringify(obj);
console.log(jsonString);  // 输出:{"name":"John","age":30}

总结

eval()函数因性能和安全隐患,在大多数场景下不推荐使用,建议使用 JSON.parse() 来替代 eval() 解析JSON数据。

到此这篇关于js如何将多个json结构组成的字符串转换为数组?的文章就介绍到这了,更多相关js转换多json结构为数组内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章