Node.js中解析无逗号分隔的多JSON对象并提取最后一个对象指定字段的方法
Node.js中解析无逗号分隔的多JSON对象并提取最后一个对象指定字段的方法
嘿,这个问题我熟!你现在面对的是无逗号分隔的连续JSON对象,这种格式没法直接用JSON.parse()搞定,不过咱们不用额外装库就能解决。
核心思路是先把这些连在一起的JSON对象逐个拆分出来,再解析成JS对象,最后取最后一个的text字段就行。这里要注意处理大括号的层级(比如你的例子里speech是嵌套对象,不能遇到单个}就拆分),具体实现如下:
代码实现
// 假设这是你拿到的包含多个JSON的原始字符串(从文件/接口获取都可以) const rawJsonStr = `{ "entities": {}, "intents": [], "speech": { "confidence": 0.4471, "tokens": [ { "confidence": 0.4471, "end": 1560, "start": 560, "token": "Кот" } ] }, "text": "Кот", "traits": {} } { "entities": {}, "intents": [], "is_final": true, "speech": { "confidence": 0.4471, "tokens": [ { "confidence": 0.4471, "end": 1560, "start": 560, "token": "Кот" } ] }, "text": "Cat", "traits": {} }`; function splitAndParseMultipleJson(rawStr) { const parsedObjects = []; let currentChunk = ''; let bracketDepth = 0; // 遍历字符串的每个字符,跟踪大括号层级 for (const char of rawStr) { currentChunk += char; if (char === '{') { bracketDepth++; } else if (char === '}') { bracketDepth--; // 当层级回到0时,说明当前chunk是一个完整的JSON对象 if (bracketDepth === 0) { try { // 解析并存入数组 const jsonObj = JSON.parse(currentChunk.trim()); parsedObjects.push(jsonObj); currentChunk = ''; // 重置chunk,准备下一个对象 } catch (err) { console.warn('跳过无效的JSON片段:', err.message); currentChunk = ''; } } } } return parsedObjects; } // 执行解析并提取最后一个对象的text字段 const allJsonObjects = splitAndParseMultipleJson(rawJsonStr); if (allJsonObjects.length > 0) { const lastTextValue = allJsonObjects.at(-1).text; // 用at(-1)取最后一个元素更直观 console.log('最后一个对象的text值:', lastTextValue); // 输出 "Cat" } else { console.log('未找到有效的JSON对象'); }
关键细节说明
- 用
bracketDepth跟踪大括号层级,确保嵌套对象不会被误拆分(比如speech里的{}不会触发拆分)。 - 每次拆分后都会尝试解析,跳过无效的JSON片段(避免单个错误影响整体)。
- 用
Array.at(-1)取最后一个元素,比[allJsonObjects.length - 1]更简洁直观(Node.js 14.0.0及以上支持)。
如果你的原始数据是从文件读取的,只需要用fs.readFileSync(同步)或fs.readFile(异步)获取字符串后,传入这个函数就行。
备注:内容来源于stack exchange,提问作者tysik
相关产品推荐
相关产品推荐

