如何在Node.js中逐对象读取未知结构JSON文件并删除指定条目
Hey there! Let's walk through each of your questions with practical, actionable Node.js examples:
Node.js's built-in fs (file system) module makes this straightforward. You can use either asynchronous (non-blocking, recommended for most cases) or synchronous (blocking, use only when necessary) methods:
Async Approach (Recommended)
This won't block your application's event loop while reading the file:
const fs = require('fs'); const path = require('path'); // Define the path to your JSON file const jsonFilePath = path.join(__dirname, 'your-json-file.json'); fs.readFile(jsonFilePath, 'utf8', (err, fileData) => { if (err) { console.error('Oops, error reading the file:', err); return; } try { // Parse the JSON string into a JavaScript array const jsonArray = JSON.parse(fileData); console.log('Successfully loaded the JSON array:', jsonArray); // You can work with jsonArray here (delete entries, loop through objects, etc.) } catch (parseError) { console.error('Failed to parse JSON:', parseError); } });
Sync Approach
Use this only if you need the file data immediately and don't mind blocking the event loop:
try { const fileData = fs.readFileSync(jsonFilePath, 'utf8'); const jsonArray = JSON.parse(fileData); console.log('Loaded JSON array synchronously:', jsonArray); } catch (err) { console.error('Error reading or parsing the file:', err); }
queryname Property Once you've parsed the JSON array, you can use the filter() method to create a new array excluding the entry with your target queryname. Then write the updated array back to the file:
// Assume jsonArray is already parsed from step 1 const targetQueryname = 'Query_1'; // Replace with the queryname you want to delete // Filter out the matching entry const updatedJsonArray = jsonArray.filter(item => item.queryname !== targetQueryname); // Write the updated array back to the file (formatted with indentation for readability) fs.writeFile( jsonFilePath, JSON.stringify(updatedJsonArray, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing the updated file:', err); return; } console.log(`Successfully deleted the entry with queryname: ${targetQueryname}`); } );
Note: filter() creates a new array instead of modifying the original, which is a safer approach for immutable data patterns.
You have two main options here, depending on the size of your JSON file:
For Standard-Sized Files (Most Cases)
Once you've parsed the full array, simply loop through it to access each object individually:
// Loop with forEach() jsonArray.forEach((obj, index) => { console.log(`Object ${index + 1}:`, obj); // Add your logic for each object here (e.g., check properties, process data) }); // Or use for...of for more control (e.g., break out of the loop early) for (const obj of jsonArray) { if (obj.name === 'John') { console.log('Found John\'s entry:', obj); break; } }
For Very Large JSON Files
If your JSON file is too big to load entirely into memory, use a streaming parser like JSONStream to read objects one at a time:
First, install the module:
npm install jsonstream
Then use it to stream the file:
const JSONStream = require('JSONStream'); const stream = fs.createReadStream(jsonFilePath, 'utf8') .pipe(JSONStream.parse('*')); // Parse each object in the top-level array // Listen for each object as it's parsed stream.on('data', (obj) => { console.log('Processing object:', obj); // Add your processing logic here }); // Listen for when the stream finishes stream.on('end', () => { console.log('Done reading all objects from the file'); }); // Handle stream errors stream.on('error', (err) => { console.error('Stream error:', err); });
内容的提问来源于stack exchange,提问作者Muthu Naaraayanan

