Utility functions for JSON.parse and JSON.stringify to work with typed arrays and array buffers.
Utility functions for JSON.parse and JSON.stringify to work with typed arrays and array buffers.
Install the library via NPM:
```npm install json-arraybuffer-reviver
Before you can use the functionality in your project, you need to import it to your project:
`js;
// Import the Price Oracle library.
import { replacer, reviver } from 'json-arraybuffer-reviver
``
When you need to JSON.stringify() or JSON.parse() data that contains ArrayBuffers, DataViews or BigInts, simply pass in the replacer and reviver functions:
`js
// Create some data to encode.
const inputData = new Uint8Array();
// Encode the data into JSON.
const encodedData = JSON.stringify(inputData, replacer);
// Decode the data from JSON.
const outputData = JSON.parse(encodedData, reviver);
`
The replacer function looks at the data that you are trying to encode into JSON and instead of using the default toString() methods it encodes the data in a human readable form as follows:
#### BigIntegers:
`js`
{
$BigInt: 'The integer number as a string'
}
#### ArrayBuffers:
`js``
{
$ArrayBuffer:
{
View: "Name of the ArrayBuffer or DataView type, as a string",
Data: "Hexadecimal representation of the bytes that make up the ArrayBuffer",
}
}
Currently, Internet Explorer and Safari browsers do not support BigIntArrays.
The code for these utility functions was inspired by a gist by Jimmy Wärting, but rebuilt from scratch in order to be:
- human readable,
- clear in purpose,
- properly documented and
- well tested.