### Makefile for Project Tasks Source: https://github.com/donutespresso/big-json/blob/main/README.md Provides essential commands for contributing to the big-json project. It includes setup for git pre-push hooks to ensure code quality before commits and a command to lint and test the code using the included Makefile. ```makefile # Install git prepush hooks make githooks # Lint and test code before committing make prepush ``` -------------------------------- ### Node.js HTTP Server for Large JSON Processing and Export Source: https://context7.com/donutespresso/big-json/llms.txt This Node.js script sets up an HTTP server that can handle large JSON uploads via POST requests to '/process' and serve large JSON datasets via GET requests to '/export'. It utilizes the 'big-json' library for efficient streaming of JSON data, preventing memory overload. The server includes error handling for parsing and stringifying JSON. It also includes a client example to demonstrate how to interact with the server. ```javascript const http = require('http'); const fs = require('fs'); const json = require('big-json'); // HTTP server that accepts large JSON POST requests const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/process') { console.log('Receiving large JSON upload...'); const parseStream = json.createParseStream(); parseStream.on('data', function(pojo) { console.log('Received complete object with', Object.keys(pojo).length, 'keys'); // Process the data const result = { receivedKeys: Object.keys(pojo).length, processedAt: new Date().toISOString(), summary: pojo }; // Stream response back json.stringify({ body: result }) .then(jsonResponse => { res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(jsonResponse) }); res.end(jsonResponse); }) .catch(err => { console.error('Stringify error:', err.message); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal server error'); }); }); parseStream.on('error', function(err) { console.error('Parse error:', err.message); res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Invalid JSON: ' + err.message); }); // Pipe request directly to parse stream req.pipe(parseStream); } else if (req.method === 'GET' && req.url === '/export') { console.log('Exporting large dataset...'); // Generate large dataset const largeDataset = { metadata: { exported: new Date().toISOString(), version: '1.0', records: 50000 }, data: [] }; for (let i = 0; i < 50000; i++) { largeDataset.data.push({ id: i, timestamp: Date.now(), value: Math.random() * 1000, status: i % 2 === 0 ? 'active' : 'inactive' }); } // Stream the response res.writeHead(200, { 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked' }); const stringifyStream = json.createStringifyStream({ body: largeDataset }); stringifyStream.on('error', function(err) { console.error('Stringify error:', err.message); res.end(); }); stringifyStream.pipe(res); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); } }); server.listen(3000, () => { console.log('Server listening on port 3000'); console.log('POST large JSON to /process'); console.log('GET large JSON from /export'); }); // Client example using the server function testServer() { const testData = { users: [], timestamp: Date.now() }; // Generate test data for (let i = 0; i < 1000; i++) { testData.users.push({ id: i, name: `User ${i}`, email: `user${i}@test.com` }); } json.stringify({ body: testData }) .then(jsonString => { const options = { hostname: 'localhost', port: 3000, path: '/process', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(jsonString) } }; const req = http.request(options, (res) => { let responseData = ''; res.on('data', (chunk) => { responseData += chunk; }); res.on('end', () => { json.parse({ body: responseData }) .then(result => { console.log('Server processed:', result.receivedKeys, 'keys'); console.log('Response:', result); }) .catch(err => { console.error('Parse response error:', err.message); }); }); }); req.on('error', (err) => { console.error('Request error:', err.message); }); req.write(jsonString); req.end(); }) } ``` -------------------------------- ### Stringify Large JavaScript Object to File Streamingly with Node.js Source: https://context7.com/donutespresso/big-json/llms.txt This code example illustrates how to use `big-json`'s `createStringifyStream` to serialize a large JavaScript object into a file without creating a complete string in memory. The stream emits JSON chunks as it processes the object, which are then piped to a write stream. It includes event listeners for data chunks, errors, and successful file writing. ```javascript const fs = require('fs'); const json = require('big-json'); // Stringify a large object to a file const largeObject = { users: [], metadata: { count: 1000000, timestamp: Date.now() } }; // Populate with large dataset for (let i = 0; i < 1000000; i++) { largeObject.users.push({ id: i, name: `User ${i}`, email: `user${i}@example.com`, created: new Date().toISOString() }); } const stringifyStream = json.createStringifyStream({ body: largeObject }); const writeStream = fs.createWriteStream('output.json'); stringifyStream.on('data', function(strChunk) { console.log(`Received chunk of ${strChunk.length} bytes`); }); stringifyStream.on('error', function(err) { console.error('Stringify error:', err.message); process.exit(1); }); stringifyStream.pipe(writeStream); writeStream.on('finish', function() { console.log('File written successfully'); }); ``` -------------------------------- ### Handle Multibyte Characters in JSON Streams Source: https://context7.com/donutespresso/big-json/llms.txt This example illustrates how to correctly handle multibyte characters (like Japanese, emojis, Chinese, and Korean) when processing JSON data chunk by chunk using streams. It serializes an object with multibyte characters, then manually splits the resulting UTF-8 string into byte chunks and pipes them to `json.createParseStream` to ensure accurate parsing. ```javascript const json = require('big-json'); // Pattern 3: Multibyte character handling const unicodeData = { japanese: "ζ—₯本θͺž", emoji: "πŸ˜€πŸŽ‰", chinese: "δΈ­ζ–‡", korean: "ν•œκ΅­μ–΄" }; json.stringify({ body: unicodeData }) .then(jsonString => { // Write as separate buffers to test multibyte handling const parseStream = json.createParseStream(); parseStream.on('data', function(pojo) { console.log('Parsed unicode data:', pojo); console.log('Japanese preserved:', pojo.japanese === unicodeData.japanese); }); // Split string into bytes and write separately const buffer = Buffer.from(jsonString, 'utf8'); for (let i = 0; i < buffer.length; i += 10) { const chunk = buffer.slice(i, Math.min(i + 10, buffer.length)); parseStream.write(chunk); } parseStream.end(); }) .catch(err => { console.error('Error:', err.message); }); ``` -------------------------------- ### createStringifyStream Source: https://github.com/donutespresso/big-json/blob/main/api.md Creates a readable stream for JSON stringification, allowing large objects to be converted to JSON strings without blocking the CPU. ```APIDOC ## createStringifyStream ### Description Create a JSON.stringify readable stream. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Request Body - **opts** (Object) - an options object - **opts.body** (Object) - the JS object to JSON.stringify ### Returns **[Stream]** - A readable stream for stringifying JSON. ### Request Example ```javascript // Example usage (conceptual) const fs = require('fs'); const createStringifyStream = require('big-json').createStringifyStream; const dataToStream = { large: 'json', object: 'here' }; const stringifyStream = createStringifyStream({ body: dataToStream }); const writeStream = fs.createWriteStream('output.json'); stringifyStream.pipe(writeStream); writeStream.on('finish', () => { console.log('JSON stringified and written to output.json'); }); ``` ### Response #### Success Response (Stream Data) - **chunk** (String) - A piece of the stringified JSON data. #### Response Example ```json { "example": "{ \"large\": \"json\", \"object\": \"here\" }" } ``` ``` -------------------------------- ### createParseStream Source: https://github.com/donutespresso/big-json/blob/main/api.md Creates a stream interface for JSON parsing, leveraging JSONStream for efficient handling of large JSON data without blocking the CPU. ```APIDOC ## createParseStream ### Description Create a JSON.parse that uses a stream interface. The underlying implementation is handled by JSONStream. This is merely a thin wrapper for convenience that handles the reconstruction/accumulation of each individually parsed field. The advantage of this approach is that by also using a streams interface, any JSON parsing or stringification of large objects won't block the CPU. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters None ### Returns **[Stream]** - A readable stream for parsing JSON. ### Request Example ```javascript // Example usage (conceptual) const fs = require('fs'); const createParseStream = require('big-json').createParseStream; const readStream = fs.createReadStream('large.json'); const parseStream = createParseStream(); readStream.pipe(parseStream); parseStream.on('data', (chunk) => { // Process parsed JSON chunk }); parseStream.on('end', () => { // All JSON parsed }); ``` ### Response #### Success Response (Stream Data) - **chunk** (Object | Array) - A piece of the parsed JSON data. #### Response Example ```json { "example": "{ \"key\": \"value\" }" } ``` ``` -------------------------------- ### _parse Source: https://github.com/donutespresso/big-json/blob/main/api.md A stream-based JSON parsing function that abstracts over streams with an async function signature, supporting both promise and callback-based usage. ```APIDOC ## _parse ### Description Stream based JSON.parse. async function signature to abstract over streams. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Request Body - **opts** (Object) - options to pass to parse stream - **opts.body** (String | Buffer) - string or buffer to parse - **callback** (Function) - a callback function ### Returns **([Object] | [Array])** - the parsed JSON. ### Request Example ```javascript // Example usage (conceptual) const _parse = require('big-json')._parse; const jsonString = '{\"key\": \"value\"}'; _parse({ body: jsonString }, (err, result) => { if (err) { console.error('Error parsing JSON:', err); } else { console.log('Parsed JSON:', result); } }); ``` ### Response #### Success Response (Parsed JSON) - **parsedData** (Object | Array) - The resulting JSON object or array. #### Response Example ```json { "example": { "key": "value" } } ``` ``` -------------------------------- ### parse Source: https://github.com/donutespresso/big-json/blob/main/api.md Provides a stream-based JSON parsing function with an async signature, supporting both promise and callback-based interactions. ```APIDOC ## parse ### Description Stream based JSON.parse. async function signature to abstract over streams. variadic arguments to support both promise and callback based usage. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Request Body - **opts** (Object) - options to pass to parse stream - **opts.body** (String) - string to parse - **callback** (Function)? - a callback function. if empty, returns a promise. ### Returns **([Object] | [Array])** - the parsed JSON. ### Request Example ```javascript // Example usage with promise: const parse = require('big-json').parse; const jsonString = '{\"key\": \"value\"}'; parse({ body: jsonString }) .then(result => console.log('Parsed JSON:', result)) .catch(err => console.error('Error parsing JSON:', err)); // Example usage with callback: parse({ body: jsonString }, (err, result) => { if (err) { console.error('Error parsing JSON:', err); } else { console.log('Parsed JSON:', result); } }); ``` ### Response #### Success Response (Parsed JSON) - **parsedData** (Object | Array) - The resulting JSON object or array. #### Response Example ```json { "example": { "key": "value" } } ``` ``` -------------------------------- ### Async Stringify API Source: https://github.com/donutespresso/big-json/blob/main/README.md Provides an asynchronous JSON.stringify function that utilizes the underlying stream implementation. Returns a Promise if no callback is provided. ```APIDOC ## stringify(opts, [callback]) ### Description An async JSON.stringify using the same underlying stream implementation. If a callback is not passed, a promise is returned. ### Method Asynchronous function call. ### Endpoint N/A (for function call) ### Parameters #### Request Body - **opts** (Object) - An options object. - **opts.body** (Object) - The object to be stringified. - **callback** (Function) - Optional. A callback function to handle the result. ### Request Example ```javascript const json = require('big-json'); const BIG_POJO = { ... }; // Your large POJO // Using Promise json.stringify({ body: BIG_POJO }) .then(str => { // handle stringified JSON }) .catch(err => { // handle error }); // Using callback json.stringify({ body: BIG_POJO }, (err, str) => { if (err) { /* handle error */ } // handle stringified JSON }); ``` ### Response #### Success Response - **Object** - The stringified JSON object. #### Response Example ```json { "example": "{\"key\": \"value\"}" } ``` ``` -------------------------------- ### Async Parse API Source: https://github.com/donutespresso/big-json/blob/main/README.md Provides an asynchronous JSON.parse function that utilizes the underlying stream implementation. Returns a Promise if no callback is provided. ```APIDOC ## parse(opts, [callback]) ### Description An async JSON.parse using the same underlying stream implementation. If a callback is not passed, a promise is returned. ### Method Asynchronous function call. ### Endpoint N/A (for function call) ### Parameters #### Request Body - **opts** (Object) - An options object. - **opts.body** (String | Buffer) - The string or buffer to be parsed. - **callback** (Function) - Optional. A callback function to handle the result. ### Request Example ```javascript const json = require('big-json'); // Using Promise json.parse({ body: '{\"key\":\"value\"}' }) .then(pojo => { // handle parsed POJO }) .catch(err => { // handle error }); // Using callback json.parse({ body: '{\"key\":\"value\"}' }, (err, pojo) => { if (err) { /* handle error */ } // handle parsed POJO }); ``` ### Response #### Success Response - **Object | Array** - The parsed JSON object or array. #### Response Example ```json { "example": "{\"key\": \"value\"}" } ``` ``` -------------------------------- ### stringify Source: https://github.com/donutespresso/big-json/blob/main/api.md A stream-based JSON stringification function with an async signature, designed for large objects and supporting both promise and callback patterns. ```APIDOC ## stringify ### Description Stream based JSON.stringify. async function signature to abstract over streams. variadic arguments to support both promise and callback based usage. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Request Body - **opts** (Object) - options to pass to stringify stream - **callback** (Function)? - a callback function. if empty, returns a promise. ### Returns **[Object]** - the parsed JSON object. ### Request Example ```javascript // Example usage with promise: const stringify = require('big-json').stringify; const jsonObject = { key: 'value', nested: { data: 123 } }; stringify({ body: jsonObject }) .then(result => console.log('Stringified JSON:', result)) .catch(err => console.error('Error stringifying JSON:', err)); // Example usage with callback: stringify({ body: jsonObject }, (err, result) => { if (err) { console.error('Error stringifying JSON:', err); } else { console.log('Stringified JSON:', result); } }); ``` ### Response #### Success Response (Stringified JSON) - **stringifiedData** (String) - The resulting JSON string. #### Response Example ```json { "example": "{ \"key\": \"value\", \"nested\": { \"data\": 123 } }" } ``` ``` -------------------------------- ### Fan-out JSON Parsing to Multiple Destinations Source: https://context7.com/donutespresso/big-json/llms.txt This pattern demonstrates how to distribute parsed JSON data from a single source stream to multiple destination streams simultaneously. It uses `fs.createReadStream` to read data, `json.createParseStream` to parse it, and then pipes the parsed objects to two separate `Transform` streams, effectively fanning out the data. ```javascript const fs = require('fs'); const json = require('big-json'); const { Transform } = require('stream'); // Pattern 2: Fan-out to multiple destinations const sourceStream = fs.createReadStream('data.json'); const parser = json.createParseStream(); const destination1 = new Transform({ objectMode: true, transform(pojo, encoding, callback) { console.log('Destination 1 received:', pojo); callback(); } }); const destination2 = new Transform({ objectMode: true, transform(pojo, encoding, callback) { console.log('Destination 2 received:', pojo); callback(); } }); // Send parsed data to multiple destinations sourceStream.pipe(parser); parser.pipe(destination1); parser.pipe(destination2); ``` -------------------------------- ### Stream Parsing API Source: https://github.com/donutespresso/big-json/blob/main/README.md API for parsing incoming streams into a POJO using a streaming approach. Supports both objects and arrays as root elements. ```APIDOC ## createParseStream() ### Description Parses an incoming stream and accumulates it into a POJO. Supports both objects and arrays as root objects for stream data. ### Method Stream-based, no explicit HTTP method. ### Endpoint N/A (for stream processing) ### Parameters None ### Request Example ```javascript const fs = require('fs'); const json = require('big-json'); const readStream = fs.createReadStream('big.json'); const parseStream = json.createParseStream(); parseStream.on('data', function(pojo) { // receive reconstructed POJO }); readStream.pipe(parseStream); ``` ### Response #### Success Response - **pojo** (Object | Array) - The reconstructed Plain Old JavaScript Object or Array. #### Response Example ```json { "example": "reconstructed POJO" } ``` ``` -------------------------------- ### Build JSON Processing Pipeline with Node.js Streams Source: https://context7.com/donutespresso/big-json/llms.txt This pattern showcases how to build a processing pipeline using Node.js streams and the big-json library. It reads a large JSON file, parses it, transforms each object, and then stringifies and writes the processed data to a new file. It utilizes `fs.createReadStream`, `json.createParseStream`, a custom `Transform` stream for processing, `json.createStringifyStream`, and `fs.createWriteStream`. ```javascript const fs = require('fs'); const json = require('big-json'); const { Transform } = require('stream'); // Pattern 1: Stream pipeline with transformation const readStream = fs.createReadStream('large-input.json'); const parseStream = json.createParseStream(); // Custom transform stream to process data const processorStream = new Transform({ objectMode: true, transform(pojo, encoding, callback) { // Process the parsed object console.log('Processing:', Object.keys(pojo).length, 'keys'); // Modify the object pojo.processed = true; pojo.processedAt = new Date().toISOString(); this.push(pojo); callback(); } }); const stringifyStream = json.createStringifyStream({ body: {} // Will be replaced by piped data }); const writeStream = fs.createWriteStream('processed-output.json'); // Chain streams together readStream .pipe(parseStream) .pipe(processorStream) .on('data', function(processedPojo) { // Create new stringify stream for processed data const outStream = json.createStringifyStream({ body: processedPojo }); outStream.pipe(writeStream); }) .on('error', function(err) { console.error('Pipeline error:', err.message); }); ``` -------------------------------- ### Async JSON Parsing with big-json Source: https://github.com/donutespresso/big-json/blob/main/README.md Shows how to asynchronously parse a JSON string or buffer using big-json's parse function. This method returns a promise that resolves with the parsed JavaScript object. It's an alternative to the stream-based approach when the entire JSON content is available as a string or buffer. ```javascript const json = require('big-json'); const jsonString = '{"name": "example", "data": [1, 2, 3]}'; // Replace with your large JSON string or Buffer async function parseLargeJson() { try { const parsedObject = await json.parse({ body: jsonString }); console.log('Async parsed object:', parsedObject); } catch (error) { console.error('Error parsing JSON:', error); } } parseLargeJson(); ``` -------------------------------- ### Stream JSON Parsing with big-json Source: https://github.com/donutespresso/big-json/blob/main/README.md Demonstrates how to parse a large JSON file using a readable stream and the big-json createParseStream function. This method is suitable for handling JSON data that might exceed memory limits if loaded all at once. It pipes the file stream into the parser stream, and the parsed JavaScript object is received in the 'data' event. ```javascript const fs = require('fs'); const path = require('path'); const json = require('big-json'); const readStream = fs.createReadStream('big.json'); const parseStream = json.createParseStream(); parseStream.on('data', function(pojo) { // => receive reconstructed POJO console.log('Parsed POJO:', pojo); }); readStream.pipe(parseStream); ``` -------------------------------- ### Stream Stringify API Source: https://github.com/donutespresso/big-json/blob/main/README.md API for stringifying a JSON object into a stream. The object is traversed and sent out in chunks. ```APIDOC ## createStringifyStream(opts) ### Description Stringifies a JSON object into a stream. The object is traversed and sent out in JSON chunks. ### Method Stream-based, no explicit HTTP method. ### Endpoint N/A (for stream processing) ### Parameters #### Request Body - **opts** (Object) - An options object. - **opts.body** (Object | Array) - The object or array to JSON.stringify. ### Request Example ```javascript const json = require('big-json'); const BIG_POJO = { ... }; // Your large POJO const stringifyStream = json.createStringifyStream({ body: BIG_POJO }); stringifyStream.on('data', function(strChunk) { // BIG_POJO will be sent out in JSON chunks as the object is traversed }); ``` ### Response #### Success Response - **strChunk** (String) - A chunk of the stringified JSON. #### Response Example ```json { "example": "{ \"key\": \"value\" }" } ``` ``` -------------------------------- ### Async JSON Stringification with big-json Source: https://github.com/donutespresso/big-json/blob/main/README.md Demonstrates how to asynchronously stringify a JavaScript object into a JSON string using big-json's stringify function. This method returns a promise that resolves with the stringified JSON. It's useful when the entire object is in memory and needs to be converted to a JSON string. ```javascript const json = require('big-json'); const largeObject = { id: 123, details: { description: 'A large object example', items: Array(1000).fill({ value: 'item' }) } }; // Replace with your large object async function stringifyLargeObject() { try { const jsonString = await json.stringify({ body: largeObject }); console.log('Async stringified JSON:', jsonString); } catch (error) { console.error('Error stringifying JSON:', error); } } stringifyLargeObject(); ``` -------------------------------- ### Stream JSON Stringification with big-json Source: https://github.com/donutespresso/big-json/blob/main/README.md Illustrates how to stringify a large JavaScript object (BIG_POJO) into a JSON string using big-json's createStringifyStream. The output is delivered in chunks, making it efficient for sending large JSON data over a stream without holding the entire string in memory. The BIG_POJO variable should be replaced with the actual large object to be stringified. ```javascript const json = require('big-json'); // Assume BIG_POJO is a large JavaScript object or array const BIG_POJO = { key1: 'value1', // ... potentially millions of key-value pairs ... keyN: 'valueN' }; const stringifyStream = json.createStringifyStream({ body: BIG_POJO }); stringifyStream.on('data', function(strChunk) { // => BIG_POJO will be sent out in JSON chunks as the object is traversed console.log('Stringified chunk:', strChunk); // You can pipe this stream to a writable stream, e.g., fs.createWriteStream('output.json') }); ``` -------------------------------- ### Parse Large JSON File Streamingly with Node.js Source: https://context7.com/donutespresso/big-json/llms.txt This snippet demonstrates how to use `big-json`'s `createParseStream` to parse a large JSON file from disk. It reads the file in chunks, processes them through the parser, and emits the fully reconstructed JavaScript object or array. Error handling is included for stream errors. ```javascript const fs = require('fs'); const json = require('big-json'); // Parse a large JSON file from disk const readStream = fs.createReadStream('big-data.json'); const parseStream = json.createParseStream(); parseStream.on('data', function(pojo) { // Receive the fully reconstructed JavaScript object console.log('Parsed object:', pojo); console.log('Number of keys:', Object.keys(pojo).length); }); parseStream.on('error', function(err) { console.error('Parse error:', err.message); process.exit(1); }); readStream.pipe(parseStream); ``` -------------------------------- ### Implement JSON Parsing with Error Recovery and Retry Source: https://context7.com/donutespresso/big-json/llms.txt This utility function demonstrates how to implement robust JSON parsing by incorporating an error recovery mechanism with retries. The `parseWithRetry` function attempts to parse JSON data, and if it fails, it retries the operation up to a specified maximum number of attempts before ultimately throwing an error. ```javascript const json = require('big-json'); // Pattern 4: Error recovery and retry function parseWithRetry(jsonData, maxRetries = 3) { let attempts = 0; function attemptParse() { return json.parse({ body: jsonData }) .catch(err => { attempts++; if (attempts < maxRetries) { console.log(`Parse failed (attempt ${attempts}), retrying...`); return attemptParse(); } throw new Error(`Failed after ${maxRetries} attempts: ${err.message}`); }); } return attemptParse(); } // Usage parseWithRetry('{"test": "data"}') .then(pojo => console.log('Success:', pojo)) .catch(err => console.error('All retries failed:', err.message)); ``` -------------------------------- ### Handle Client Errors in JavaScript Source: https://context7.com/donutespresso/big-json/llms.txt This JavaScript snippet demonstrates error handling for client-side operations, likely within a Node.js application. It logs any encountered errors to the console, specifically catching issues during data processing or network communication. This is crucial for debugging and monitoring application behavior. ```javascript .catch(err => { console.error('Client error:', err.message); }); } ``` -------------------------------- ### Async JSON Stringifying with Big-JSON Source: https://context7.com/donutespresso/big-json/llms.txt Converts a JavaScript object or array into a JSON string asynchronously. Supports callback and Promise APIs, ideal for large data that exceeds V8's string limits. Input is an object with a 'body' property containing the data to stringify. ```javascript const json = require('big-json'); const complexObject = { artist: "The Beatles", album: "Sgt Pepper Lonely Hearts Club Band", year: 1967, genre: "Rock", tracks: [ { name: "Sgt Pepper's Lonely Hearts Club Band" }, { name: "With A Little Help From My Friends" } ], comments: "What I can't even" }; // Callback-based usage json.stringify({ body: complexObject }, function(err, jsonString) { if (err) { console.error('Stringify error:', err.message); return; } console.log('JSON output:', jsonString); console.log('String length:', jsonString.length); }); // Promise-based usage with chaining json.stringify({ body: complexObject }) .then(jsonString => { console.log('Stringified successfully'); return JSON.parse(jsonString); // Verify round-trip }) .then(parsed => { console.log('Round-trip successful:', parsed.artist); }) .catch(err => { console.error('Error:', err.message); }); // Handling arrays const largeArray = []; for (let i = 0; i < 100000; i++) { largeArray.push({ id: i, value: Math.random() }); } json.stringify({ body: largeArray }) .then(jsonString => { console.log(`Array stringified: ${jsonString.length} bytes`); }) .catch(err => { console.error('Error:', err.message); }); // Handling repeated object references const sharedObject = { name: 'shared', value: 42 }; const arrayWithDuplicates = [sharedObject, sharedObject, sharedObject]; json.stringify({ body: arrayWithDuplicates }) .then(jsonString => { console.log('Output:', jsonString); // Output: [{"name":"shared","value":42},{"name":"shared","value":42},{"name":"shared","value":42}] }) .catch(err => { console.error('Error:', err.message); }); ``` -------------------------------- ### Async JSON Parsing with Big-JSON Source: https://context7.com/donutespresso/big-json/llms.txt Parses a JSON string or Buffer into a JavaScript object asynchronously. Supports callback and Promise APIs. Handles potential errors during parsing. Input is expected as an object with a 'body' property containing the JSON data. ```javascript const json = require('big-json'); const fs = require('fs'); // Callback-based usage const jsonString = fs.readFileSync('data.json', 'utf8'); json.parse({ body: jsonString }, function(err, pojo) { if (err) { console.error('Parse error:', err.message); return; } console.log('Parsed successfully:', pojo); }); // Promise-based usage json.parse({ body: jsonString }) .then(pojo => { console.log('Artist:', pojo.artist); console.log('Album:', pojo.album); console.log('Tracks:', pojo.tracks.length); return pojo; }) .catch(err => { console.error('Parse error:', err.message); process.exit(1); }); // Buffer support - useful for network data const buffer = Buffer.from('{"name":"test","value":123}', 'utf8'); json.parse({ body: buffer }) .then(pojo => { console.log('Parsed from buffer:', pojo); }) .catch(err => { console.error('Error:', err.message); }); // Error handling with invalid JSON const invalidJson = '{"name": "test", "value": '; json.parse({ body: invalidJson }) .then(pojo => { console.log('Success:', pojo); }) .catch(err => { console.error('Expected error caught:', err.message); // Output: Expected error caught: Invalid JSON (Unexpected end of input) }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.