JSON文件开头带点导致无法遍历,如何清理并实现正常遍历?
问题:JSON数据开头带句点导致无法遍历的解决方法
问题说明
从API获取的响应文本开头带有英文句点(.),直接处理时无法正确解析为JSON对象,遍历操作返回大量undefined,需要清理该句点并正确解析数据。
原代码
// Fetch API fetch(apiUrl, { method: "POST", headers: headers, body: JSON.stringify(requestBody), }) .then(response => response.json()) .then(data => { // Get the generated response from the API const generatedResponse = data.choices[0].text; // Console log out response console.log("smartResponse:: ", generatedResponse); for (let section in generatedResponse) { // Get the prompt for the current section let prompt = generatedResponse[section].prompt; // Do something with the prompt, like print it to the console console.log(`Prompt for ${section}: ${prompt}`); } })
原执行输出
smartResponse:: . { "whatIsABox": { "prompt": "What is a box?", "section": "What is a box?" }, "typesOfBoxes": { "prompt": "What are the different types of boxes?", "section": "Types of Boxes" }, "usesForBoxes": { "prompt": "What are some uses for boxes?", "section": "Uses for Boxes" } } Prompt for 0: undefined Prompt for 1: undefined Prompt for 2: undefined Prompt for 3: undefined Prompt for 4: undefined
解决方案
关键修改点
- 清理响应文本:移除开头的句点和多余空白字符
- 将清理后的字符串解析为JSON对象
- 遍历解析后的对象获取正确数据
修改后的完整代码
// Fetch API fetch(apiUrl, { method: "POST", headers: headers, body: JSON.stringify(requestBody), }) .then(response => response.json()) .then(data => { // Get the generated response from the API let generatedResponse = data.choices[0].text; // 清理开头的句点和前后空白 const cleanedResponse = generatedResponse.trim().replace(/^\./, '').trim(); // Console log out cleaned response console.log("smartResponse:: ", cleanedResponse); // 解析为JSON对象 const parsedData = JSON.parse(cleanedResponse); // 遍历解析后的对象 for (let key in parsedData) { if (parsedData.hasOwnProperty(key)) { const section = parsedData[key]; // 按期望格式输出,可替换为实际回答字段 console.log(`Prompt for ${section.section}: ${section.prompt}`); } } }) .catch(error => console.error("Error processing data:", error));
代码说明
trim():移除字符串前后的空白字符(包括换行、空格)replace(/^\./, ''):用正则匹配开头的句点并替换为空JSON.parse():将清理后的合法JSON字符串转换为JavaScript对象,此时才能通过键值对获取数据hasOwnProperty(key):避免遍历对象原型链上的属性,确保只处理目标数据
期望输出
smartResponse:: { "whatIsABox": { "prompt": "What is a box?", "section": "What is a box?" }, "typesOfBoxes": { "prompt": "What are the different types of boxes?", "section": "Types of Boxes" }, "usesForBoxes": { "prompt": "What are some uses for boxes?", "section": "Uses for Boxes" } } Prompt for What is a box?: What is a box? Prompt for Types of Boxes: What are the different types of boxes? Prompt for Uses for Boxes: What are some uses for boxes?
内容的提问来源于stack exchange,提问作者SirBT
相关产品推荐
相关产品推荐

