Node.js中如何将文本文件转换为JavaScript数组?
Hey there! The problem here is that your myJson.txt file doesn’t contain valid JSON—it’s just a sequence of separate JSON objects stuck together without proper array formatting. Let’s fix that and get your code working.
Step 1: Understand the Input Problem
Your file content looks like this:
{"action": "key press", "timestamp": 1523783621, "user": "neovim"} {"action": "unlike", "timestamp": 1523784584, "user": "r00k"} {"action": "touch", "timestamp": 1523784963, "user": "eevee"} {"action": "report as spam", "timestamp": 1523786005, "user": "moxie"}
This isn’t a valid JSON array because:
- It’s not wrapped in square brackets
[] - Individual objects are separated by spaces instead of commas
,
Step 2: Working Code Solution
Here’s a complete function that reads the file, fixes the JSON format, and parses it into a valid JavaScript array:
const fs = require('fs'); function convert(input_file_path) { try { // Read the raw file content const fileContent = fs.readFileSync(input_file_path, 'utf8'); // Transform the invalid JSON into a valid array: // 1. Replace "} {" (with any whitespace in between) with "}, {" // 2. Wrap the entire string in square brackets const validJson = `[${fileContent.replace(/}\s*{/g, '}, {')}]`; // Parse into a JavaScript array of objects const dataArray = JSON.parse(validJson); return dataArray; } catch (error) { console.error('Something went wrong:', error.message); return null; } } // Example usage const convertedArray = convert('./myJson.txt'); if (convertedArray) { console.log('Success! Your array:', convertedArray); }
How This Works:
- Reading the File: We use
fs.readFileSyncfor simplicity (swap tofs.readFilewith a callback if you need async behavior). - Fixing the JSON: The regex
/\}\s*\{\/gfinds every instance of}followed by any whitespace (spaces, newlines, tabs) and{, replacing it with}, {to properly separate objects. Wrapping the whole string in[]turns it into a valid JSON array. - Parsing:
JSON.parseconverts the corrected JSON string into a usable JavaScript array. - Error Handling: The try/catch block catches common issues like missing files or malformed JSON (even after our fix) and logs a clear message.
内容的提问来源于stack exchange,提问作者Viet Le

