stringify
is an alias fortoString
parse
is an alias forfromString
debug
is an alias fortoReadableString
serialize
is an alias fortoBytes
deserialize
is an alias forfromBytes
Examples assume the module is loaded like this
const json = require('@whi/json');
The replacer
callback is given the parent's key and the current value. this
is set to the
parent object in-case you need access to it (ergo this[key] == value
).
Example of replacing Uint8Array
with Array
function replacer (key, value) {
if ( value instanceof Uint8Array )
return [].slice.call(value);
return value;
}
The reviver
callback is given the parent's key and the current value. this
is set to the parent
object in-case you need access to it (ergo this[key] == value
).
Example of reviving Buffer
function reviver (key, value) {
if ( typeof value === "object" && value !== null && value.type === "Buffer" )
return Buffer.from( value.data );
return value;
}
JSON encode a value.
Differences from JSON.stringify
- Handles Typed Array Views like Node.js Buffer.toJSON()
- Keys are ordered by default but can be disabled via the 4th argument
Deserialize JSON back into object form.
Differences from JSON.parse
- Revives serialized Typed Array Views
- Revives
Buffer
if present; otherwise, falls back toUint8Array
- Revives
Date
objects if a string matches the ISO date format
JSON encode a value with more human readable replacements. Several formatting features were inspired by Node's REPL formatting.
indent
- takes anoptions
object insteadoptions.indent
- override default indent valueoptions.truncate_views
- how many values to display forArrayBuffer
views (default: 50)
Differences from toString
- Formats Buffers like Node's REPL
- eg.
<Buffer 48 65 6c 6c 6f>
- eg.
- Formats Typed Array
Views
- eg.
Uint8Array { 72, 101, 108, 108, 111 }
- eg.
- Handles
BigInt
- Replaces circular references with
[Circular]
Runs a value
through toString
and then uses the built-in UTF-8 TextEncoder
to return a
Uint8Array
.
Uses the built-in UTF-8 TextDecoder
to process Uint8Array
input. Then runs the result through
fromString
.