API Reference
jsonReader
The main function for processing streaming JSON data. It yields progressively more complete JSON objects as data arrives.
JAVASCRIPT
import { jsonReader } from '@formkit/jsonreader';
for await (const partialData of jsonReader(reader)) {
// Process the partial data
console.log(partialData);
}
Parameters
Parameter | Type | Description |
---|---|---|
reader | ReadableStreamDefaultReader | A reader object from a readable stream, typically obtained from response.body.getReader() . |
options | Object (optional) | Configuration options for the reader. |
Options
Option | Type | Description |
---|---|---|
required | string[] | Array of paths that must be present before yielding a result. |
silent | string[] | Array of paths to exclude from the yielded results. |
assign | Object | Object with properties to add to each yielded result. |
Advanced Usage
Using options to customize behavior:
JAVASCRIPT
import { jsonReader } from '@formkit/jsonreader';
for await (const partialData of jsonReader(reader, {
// Only yield when these properties are present
required: ['status', 'results', 'metadata.timing'],
// Don't include these properties in results
silent: ['sensitiveData'],
// Add these properties to each yielded object
assign: {
timestamp: Date.now(),
requestId: '12345'
}
})) {
updateUI(partialData);
}
jsonPathReader
A specialized function for extracting values from specific JSON paths as data arrives. This is useful when you only care about certain paths within a larger JSON structure.
JAVASCRIPT
import { jsonPathReader } from '@formkit/jsonreader';
const reader = response.body.getReader();
const paths = [
'results',
'metadata.timing',
'users.*.name' // Wildcard to match names of all users
];
for await (const [value, path] of jsonPathReader(reader, paths)) {
// Each iteration yields a specific value and its path as a tuple
console.log(`Path: ${path}, Value:`, value);
if (path === 'results' && Array.isArray(value)) {
// Handle results array
renderResults(value);
} else if (path.startsWith('users.') && path.endsWith('.name')) {
// Handle individual user names matched by wildcard
updateUserName(path.split('.')[1], value);
}
}
Parameters
Parameter | Type | Description |
---|---|---|
reader | ReadableStreamDefaultReader | A reader object from a readable stream, typically obtained from response.body.getReader() . |
paths | string[] | string | One or more path strings to extract from the JSON data. For example, ['results', 'metadata.timing'] or 'results' . You can use '*' as a wildcard path segment to match any property or array item at that location (e.g., 'users.*.name' or 'items.*.id' ). |
Return Value
The jsonPathReader
function returns an async generator that yields tuples containing:
Element | Type | Description |
---|---|---|
value (index 0) | any | The value found at the matching path. |
path (index 1) | string | The specific path from your provided paths array that was matched. |
Advanced Usage Example
JAVASCRIPT
import { jsonPathReader } from '@formkit/jsonreader';
async function searchWithRealtimeResults() {
const response = await fetch('https://api.search-service.com/search?q=jsonreader');
const reader = response.body.getReader();
let resultCount = 0;
let lastTimingUpdate = null;
// Monitor both search results and timing information
for await (const [value, path] of jsonPathReader(reader, [
'results',
'metadata.timing',
'status'
])) {
if (path === 'results' && Array.isArray(value)) {
// New results have arrived
const newResults = value.slice(resultCount);
resultCount = value.length;
// Update the UI with just the new results
appendResultsToUI(newResults);
updateResultCounter(resultCount);
}
if (path === 'metadata.timing') {
// Update performance metrics in real-time
lastTimingUpdate = value;
updateTimingDisplay(value);
}
if (path === 'status' && value === 'complete') {
// Search is done
showCompletionMessage();
}
}
}
Error Handling
jsonReader and jsonPathReader will throw an error when parsing fails. You should use a try/catch block to handle these errors:
JAVASCRIPT
try {
for await (const data of jsonReader(reader)) {
// Process data
console.log(data);
}
} catch (error) {
// Handle error
console.error('JSON parsing error:', error);
}