JSON parse & stringify that supports binary via base64 encoding
npx @tessl/cli install tessl/npm-json-buffer@3.0.00
# JSON Buffer
1
2
## Overview
3
4
JSON functions that support Node.js Buffer objects by converting them to base64 encoding during serialization and restoring them during parsing. Unlike standard JSON.stringify which converts Buffers to arrays, json-buffer preserves the binary nature of data.
5
6
## Package Information
7
8
- **Package Name**: json-buffer
9
- **Package Type**: npm
10
- **Language**: JavaScript (Node.js)
11
- **Installation**: `npm install json-buffer`
12
13
## Core Imports
14
15
```javascript
16
const JSONB = require('json-buffer');
17
```
18
19
ES6 modules:
20
21
```javascript
22
import * as JSONB from 'json-buffer';
23
// or
24
import { stringify, parse } from 'json-buffer';
25
```
26
27
## Basic Usage
28
29
```javascript
30
const JSONB = require('json-buffer');
31
const Buffer = require('buffer').Buffer;
32
33
// Create a buffer with binary data
34
const buffer = Buffer.from('hello there!');
35
const data = { message: buffer, type: 'greeting' };
36
37
// Stringify with Buffer support
38
const jsonString = JSONB.stringify(data);
39
console.log(jsonString);
40
// Output: {"message":":base64:aGVsbG8gdGhlcmUh","type":"greeting"}
41
42
// Parse back to original structure with Buffer restored
43
const parsed = JSONB.parse(jsonString);
44
console.log(parsed.message instanceof Buffer); // true
45
console.log(parsed.message.toString()); // "hello there!"
46
```
47
48
## Capabilities
49
50
### JSON Stringification with Buffer Support
51
52
Converts JavaScript values to JSON strings with special handling for Buffer objects.
53
54
```javascript { .api }
55
/**
56
* Stringify JavaScript values with Buffer support
57
* @param {any} o - The value to stringify
58
* @returns {string|undefined} JSON string representation, or undefined if input is undefined
59
*/
60
function stringify(o)
61
```
62
63
**Special Behavior:**
64
- **Buffer objects**: Converted to base64 strings prefixed with `:base64:`
65
- **String escaping**: Strings starting with `:` are escaped by prefixing with another `:`
66
- **toJSON support**: Objects with toJSON methods are processed via toJSON
67
- **Function filtering**: Functions are ignored during serialization
68
- **Undefined handling**: Undefined object properties are ignored, undefined array elements become null
69
- **Undefined input**: Returns undefined if input is undefined
70
71
**Usage Examples:**
72
73
```javascript
74
const JSONB = require('json-buffer');
75
76
// Buffer handling
77
const buffer = Buffer.from('binary data');
78
JSONB.stringify(buffer);
79
// Returns: ":base64:YmluYXJ5IGRhdGE="
80
81
// String escaping
82
JSONB.stringify(':special string');
83
// Returns: "::special string"
84
85
// Complex objects
86
const data = {
87
text: 'hello',
88
binary: Buffer.from('world'),
89
nested: { value: 42 }
90
};
91
JSONB.stringify(data);
92
// Returns: {"text":"hello","binary":":base64:d29ybGQ=","nested":{"value":42}}
93
94
// Array with undefined
95
JSONB.stringify([1, undefined, Buffer.from('test')]);
96
// Returns: [1,null,":base64:dGVzdA=="]
97
```
98
99
### JSON Parsing with Buffer Restoration
100
101
Parses JSON strings back to JavaScript values with automatic Buffer restoration.
102
103
```javascript { .api }
104
/**
105
* Parse JSON strings with Buffer restoration
106
* @param {string} s - The JSON string to parse
107
* @returns {any} Parsed JavaScript value with Buffers restored
108
*/
109
function parse(s)
110
```
111
112
**Special Behavior:**
113
- **Buffer restoration**: Strings with `:base64:` prefix are converted back to Buffer objects using base64 decoding
114
- **String unescaping**: Strings starting with `:` have the first `:` removed
115
- **Standard JSON**: Uses JSON.parse with custom reviver function for Buffer handling
116
- **Error propagation**: Invalid JSON throws SyntaxError from underlying JSON.parse
117
118
**Usage Examples:**
119
120
```javascript
121
const JSONB = require('json-buffer');
122
123
// Buffer restoration
124
const jsonString = '":base64:aGVsbG8="';
125
const result = JSONB.parse(jsonString);
126
console.log(result instanceof Buffer); // true
127
console.log(result.toString()); // "hello"
128
129
// String unescaping
130
const escapedString = '"::special string"';
131
const unescaped = JSONB.parse(escapedString);
132
console.log(unescaped); // ":special string"
133
134
// Complex object parsing
135
const complexJson = '{"text":"hello","binary":":base64:d29ybGQ=","nested":{"value":42}}';
136
const parsed = JSONB.parse(complexJson);
137
console.log(parsed.text); // "hello"
138
console.log(parsed.binary instanceof Buffer); // true
139
console.log(parsed.binary.toString()); // "world"
140
console.log(parsed.nested.value); // 42
141
```
142
143
## Error Handling
144
145
The package relies on standard JSON error handling:
146
147
- **SyntaxError**: Thrown by `parse()` when given invalid JSON strings
148
- **TypeError**: Thrown by `stringify()` for circular references (same as JSON.stringify)
149
150
```javascript
151
const JSONB = require('json-buffer');
152
153
try {
154
JSONB.parse('invalid json');
155
} catch (error) {
156
console.log(error instanceof SyntaxError); // true
157
}
158
159
// Circular reference error
160
const circular = {};
161
circular.self = circular;
162
try {
163
JSONB.stringify(circular);
164
} catch (error) {
165
console.log(error instanceof TypeError); // true
166
}
167
```
168
169
## Types
170
171
```javascript { .api }
172
/**
173
* Buffer class from Node.js (built-in)
174
* Used for handling binary data
175
*/
176
class Buffer {
177
/**
178
* Creates a Buffer from various data types
179
* @param {string|number[]|ArrayBuffer} data - The data to create Buffer from
180
* @param {string} [encoding] - The encoding to use (e.g., 'base64', 'utf8')
181
* @returns {Buffer} New Buffer instance
182
*/
183
static from(data, encoding);
184
185
/**
186
* Converts Buffer to string representation
187
* @param {string} [encoding] - The encoding to use (default: 'utf8')
188
* @returns {string} String representation of the Buffer
189
*/
190
toString(encoding);
191
192
/**
193
* Checks if an object is a Buffer instance
194
* @param {any} obj - Object to check
195
* @returns {boolean} True if obj is a Buffer
196
*/
197
static isBuffer(obj);
198
}
199
```