@unikvs/json
How to use @unikvs/json, middleware that serializes values as JSON (JSON Lines for streams).
Overview
Middleware that serializes values as JSON. Middleware
Single reads/writes convert a value directly to a JSON string, while streams convert each item to one JSON Lines row.
nameis"Json".isOpenis alwaystrue.
Install with:
npm install @unikvs/jsonpnpm add @unikvs/jsonyarn add @unikvs/jsonbun add @unikvs/jsonnub add @unikvs/jsonaube add @unikvs/jsonUsage
Json implements IMiddleware. Pass it to UniKvs with use().
import { Json } from "@unikvs/json";
The following example stores an object as JSON and restores its original shape on read.
import { Json } from "@unikvs/json";
import { Memory } from "@unikvs/memory";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{ greeting: unikvs.Value<{ readonly text: string }> }>()
.use(new Json())
.persist(new Memory())
.build();
await kvs.open();
await kvs.set("greeting", { text: "hello" });
const greeting = await kvs.get("greeting");
await kvs.close();
Data types
| Method | Input | Output |
|---|---|---|
encode |
unknown |
Uint8Array<ArrayBuffer> |
decode |
Uint8Array<ArrayBuffer> |
unknown |
encodeStream |
unknown |
Uint8Array<ArrayBuffer> |
decodeStream |
Uint8Array<ArrayBuffer> |
unknown |
encodeconverts a value to a JSON string and encodes it as UTF-8 bytes.decodeconverts bytes back to a UTF-8 string and parses it as JSON.encodeStreamemits one line per input item (<JSON>\n) in JSON Lines format.decodeStreambuffers received bytes as a string and parses lines as newlines become available.- One trailing CR is stripped per line, and empty lines are skipped.
- If there is no trailing newline, the remaining buffer is processed as the final line.
Errors
Errors thrown by this package:
JsonUnsupportedValueError
Values for which JSON.stringify returns undefined cannot be represented as JSON, so this middleware cannot encode them.
typestring
`typeof` of the value being converted.
stringMeaning
Passing undefined, functions, symbols, or similar as the root value throws this error. meta.type holds the target’s typeof.
How to fix
Pass a JSON-representable value such as an object, array, string, number, boolean, or null.
Invalid JSON or UTF-8 received while decoding propagates native errors such as SyntaxError unchanged.