### Stream JSON File with JSONParse Source: https://context7.com/creationix/jsonparse/llms.txt Feeds data chunks to the parser incrementally using the `write()` method, enabling streaming processing of large JSON documents or network streams. This example demonstrates overriding the `onValue` handler to capture parsed values from a file stream. ```javascript var Parser = require('jsonparse'); var fs = require('fs'); var p = new Parser(); var results = []; // Override onValue to capture parsed values p.onValue = function(value) { if (this.stack.length === 0) { // Top-level value completely parsed results.push(value); } }; // Stream large JSON file in chunks var stream = fs.createReadStream('large-data.json'); stream.on('data', function(chunk) { p.write(chunk); }); stream.on('end', function() { console.log('Parsed results:', results); }); // Can also write strings p.write('{"partial":'); p.write('"data"}'); ``` -------------------------------- ### Extract Specific Fields from Nested JSON Selectively Source: https://context7.com/creationix/jsonparse/llms.txt This example shows how to extract only specific fields from deeply nested JSON structures without parsing the entire object into memory. It uses the `jsonparse` library's event-driven approach to target desired fields based on their keys and nesting depth, building a new, smaller object with only the extracted data. ```javascript var Parser = require('jsonparse'); var p = new Parser(); // Extract only specific fields from large dataset var records = []; var currentRecord = {}; p.onValue = function(value) { var depth = this.stack.length; var key = this.key; // Array of user objects at root level if (depth === 1) { // Inside user object if (key === 'id' || key === 'email' || key === 'lastLogin') { currentRecord[key] = value; } } // Nested address.city field if (depth === 2 && this.stack[1].key === 'address' && key === 'city') { currentRecord.city = value; } // Complete user object parsed if (depth === 0 && typeof value === 'object') { if (Object.keys(currentRecord).length > 0) { records.push(currentRecord); currentRecord = {}; } } }; // Parse large user dataset, extracting only needed fields var json = JSON.stringify([ { id: 1, email: 'alice@example.com', password: 'secret', // Not extracted profile: { bio: '...' }, // Not extracted address: { city: 'NYC', street: '...' }, // Only city extracted lastLogin: '2025-01-15' }, // ... thousands more users ]); p.write(json); console.log('Extracted', records.length, 'records'); console.log('Memory-efficient records:', records); // Output: [{ id: 1, email: 'alice@example.com', city: 'NYC', lastLogin: '2025-01-15' }, ...] ``` -------------------------------- ### Instantiate JSONParse Parser Source: https://context7.com/creationix/jsonparse/llms.txt Creates a new streaming JSON parser instance. Basic usage involves writing complete JSON strings to the parser and observing its output. This method is fundamental for initializing the parser for subsequent data processing. ```javascript var Parser = require('jsonparse'); var p = new Parser(); // Basic usage - parse complete JSON strings p.write('{"name": "John", "age": 30}'); p.write('[1, 2, 3, 4, 5]'); p.write('null'); p.write('true'); p.write('"Hello World"'); ``` -------------------------------- ### Low-Level JSON Token Parsing with JSONParse Source: https://context7.com/creationix/jsonparse/llms.txt Provides a low-level callback using the `onToken` event handler that fires for each JSON token (braces, brackets, strings, numbers, etc.). This enables custom parsing logic by inspecting individual tokens and their values. ```javascript var Parser = require('jsonparse'); var p = new Parser(); var tokenLog = []; // Override onToken for low-level parsing control p.onToken = function(token, value) { // Token constants available as Parser.C var C = Parser.C; switch(token) { case C.LEFT_BRACE: tokenLog.push('Start object'); break; case C.RIGHT_BRACE: tokenLog.push('End object'); break; case C.LEFT_BRACKET: tokenLog.push('Start array'); break; case C.RIGHT_BRACKET: tokenLog.push('End array'); break; case C.STRING: tokenLog.push('String: ' + value); break; case C.NUMBER: tokenLog.push('Number: ' + value); break; case C.TRUE: tokenLog.push('Boolean: true'); break; case C.FALSE: tokenLog.push('Boolean: false'); break; case C.NULL: tokenLog.push('Null'); break; } }; p.write('{"active": true, "count": 42, "tags": ["a", "b"]}'); console.log(tokenLog); // Output: ['Start object', 'String: active', 'Boolean: true', ...] ``` -------------------------------- ### Using jsonparse Parser Constants Source: https://context7.com/creationix/jsonparse/llms.txt Access predefined token and state constants provided by the `jsonparse` library. These constants are useful for implementing custom parsing logic that interacts with the parser at a low level, such as handling specific token types or parser states. ```javascript var Parser = require('jsonparse'); // Token constants var C = Parser.C; console.log('Token types:'); console.log('LEFT_BRACE:', C.LEFT_BRACE); // { console.log('RIGHT_BRACE:', C.RIGHT_BRACE); // } console.log('LEFT_BRACKET:', C.LEFT_BRACKET); // [ console.log('RIGHT_BRACKET:', C.RIGHT_BRACKET); // ] console.log('COLON:', C.COLON); // : console.log('COMMA:', C.COMMA); // , console.log('TRUE:', C.TRUE); // true console.log('FALSE:', C.FALSE); // false console.log('NULL:', C.NULL); // null console.log('STRING:', C.STRING); // "string" console.log('NUMBER:', C.NUMBER); // 123 console.log('\nParser states:'); console.log('VALUE:', C.VALUE); // Expecting a value console.log('KEY:', C.KEY); // Expecting object key console.log('OBJECT:', C.OBJECT); // Inside object console.log('ARRAY:', C.ARRAY); // Inside array ``` -------------------------------- ### Stream Large JSON Files Efficiently with Node.js Source: https://context7.com/creationix/jsonparse/llms.txt This snippet demonstrates parsing large JSON files by streaming them in chunks using Node.js. It utilizes the `jsonparse` library and Node.js `fs` streams to process data without loading the entire file into memory. It handles data chunks, value emissions, and errors, providing parsed results or error information via a callback. ```javascript var Parser = require('jsonparse'); var fs = require('fs'); function parseJsonFile(filePath, callback) { var p = new Parser(); var results = []; var errors = []; p.onValue = function(value) { if (this.stack.length === 0) { results.push(value); } }; p.onError = function(err) { errors.push(err); }; var stream = fs.createReadStream(filePath, { encoding: 'utf8', highWaterMark: 16384 // 16KB chunks }); stream.on('data', function(chunk) { p.write(chunk); }); stream.on('end', function() { if (errors.length > 0) { callback(errors[0], null); } else { callback(null, results); } }); stream.on('error', function(err) { callback(err, null); }); } // Usage parseJsonFile('./large-data.json', function(err, data) { if (err) { console.error('Failed to parse:', err.message); } else { console.log('Parsed', data.length, 'top-level items'); console.log('First item:', data[0]); } }); ``` -------------------------------- ### Accessing jsonparse Parser State Source: https://context7.com/creationix/jsonparse/llms.txt Access internal parser state properties such as `stack`, `key`, `value`, `state`, and `mode` to track nesting depth, current parsing position, and the structure of complex JSON data. This is useful for debugging or building custom logic based on the parsing context. ```javascript var Parser = require('jsonparse'); var p = new Parser(); p.onValue = function(value) { // this.stack: array of parent objects/arrays // this.key: current property name or array index // this.value: current container being built // this.state: parser state (VALUE, KEY, COLON, COMMA) // this.mode: container mode (OBJECT or ARRAY) var path = this.stack .slice(1) .map(function(item) { return item.key; }) .concat(this.key !== undefined ? [this.key] : []); console.log('Path:', path.join('.'), '=', JSON.stringify(value)); console.log('Depth:', this.stack.length); }; p.write('{"users": [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]}'); // Output: // Path: users.0.name = "Alice" // Depth: 2 // Path: users.0.age = 30 // Depth: 2 // ... ``` -------------------------------- ### Custom Error Handling with JSONParse Source: https://context7.com/creationix/jsonparse/llms.txt Implements custom error handling by overriding the `onError` event handler. This allows developers to manage parsing errors gracefully without the parser throwing exceptions, enabling continued processing where possible. ```javascript var Parser = require('jsonparse'); var p = new Parser(); var errors = []; // Custom error handling p.onError = function(err) { errors.push({ message: err.message, timestamp: Date.now() }); // Don't throw - continue processing if possible console.error('Parse error:', err.message); }; // Try parsing invalid JSON p.write('{"invalid": }'); p.write('{"valid": "data"}'); console.log('Errors encountered:', errors.length); ``` -------------------------------- ### Streaming HTTP Response with jsonparse Source: https://context7.com/creationix/jsonparse/llms.txt Process JSON data from HTTP streams without buffering the entire response. This is ideal for handling large API responses or continuous data streams, allowing for incremental parsing and processing as data arrives. ```javascript var Parser = require('jsonparse'); var http = require('http'); var p = new Parser(); var itemCount = 0; // Extract data from continuous JSON stream p.onValue = function(value) { // Process items at specific depth if (this.stack.length === 1) { itemCount++; console.log('Item', itemCount, ':', value); // Can stop stream early if needed if (itemCount >= 10) { response.destroy(); } } }; p.onError = function(err) { console.error('Stream parsing error:', err.message); }; var request = http.get('http://api.example.com/stream', function(response) { console.log('Status:', response.statusCode); response.on('data', function(chunk) { try { p.write(chunk); } catch(e) { console.error('Parse failed:', e.message); response.destroy(); } }); response.on('end', function() { console.log('Stream complete. Total items:', itemCount); }); response.on('error', function(err) { console.error('HTTP error:', err.message); }); }); request.on('error', function(err) { console.error('Request failed:', err.message); }); ``` -------------------------------- ### Extract Nested JSON Values with JSONParse Source: https://context7.com/creationix/jsonparse/llms.txt Utilizes the `onValue` event handler to extract specific nested fields from streaming JSON data. The parser's stack and key properties are used to navigate the JSON structure, allowing targeted data extraction without full document parsing. ```javascript var Parser = require('jsonparse'); var http = require('http'); var p = new Parser(); var tweets = []; // Extract specific nested fields from streaming JSON p.onValue = function(value) { // this.stack contains the nesting hierarchy // this.key is the current property name or array index // Extract tweet text (at tweets[i].text) if (this.stack.length === 1 && this.key === 'text') { var tweet = { text: value }; tweets.push(tweet); } // Extract user name (at tweets[i].user.name) if (this.stack.length === 2 && this.key === 'name' && this.stack[1].key === 'user') { tweets[tweets.length - 1].userName = value; } // Detect when full object is parsed if (this.stack.length === 0) { console.log('Complete document parsed:', value); } }; // Process HTTP stream http.get('http://api.example.com/feed', function(res) { res.on('data', function(chunk) { p.write(chunk); }); }); ``` -------------------------------- ### Custom Number Parsing with jsonparse Source: https://context7.com/creationix/jsonparse/llms.txt Implement custom number parsing logic, particularly useful for handling large integers that may lose precision with standard JavaScript Number types or for supporting special numeric formats. This method is called by the parser when a number token is encountered. ```javascript var Parser = require('jsonparse'); var p = new Parser(); // Custom number parsing for BigInt support p.numberReviver = function(text) { var result = Number(text); if (isNaN(result)) { return this.charError(buffer, i); } // Detect large integers that lose precision if (text.match(/^-?[0-9]+$/) && result.toString() !== text) { // Treat as string to preserve precision console.log('Large integer detected, preserving as string:', text); this.onToken(Parser.C.STRING, text); } else { this.onToken(Parser.C.NUMBER, result); } }; p.onValue = function(value) { if (this.stack.length === 0) { console.log('Value:', value, 'Type:', typeof value); } }; // JavaScript Number loses precision for large integers p.write('[9007199254740992]'); // Max safe integer + 1 p.write('[7161093205057351174]'); // Becomes string automatically ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.