@bitty/json

Types and type-safe functions for JSON.
Installation
This library is published in the NPM registry and can be installed using any compatible package manager.
npm install @bitty/json --save
yarn add @bitty/json
Installation from CDN
This module has a UMD bundle available through JSDelivr and Unpkg CDNs.
<script src="https://unpkg.com/@bitty/json"></script>
<script src="https://cdn.jsdelivr.net/npm/@bitty/json"></script>
<script>
console.log(Json);
console.log(Json.toJson({ name: 'Carlos Marcos' }, 0));
</script>
Getting Stated
This module named exports functions and types to type-safely handle JSON.
import { JsonObject, toJson } from '@bitty/json';
const sendJson = <T extends JsonObject = JsonObject>(obj: T) => {
const json = toJson(obj);
};
sendJson<{ names: Set<string> }>({ ... });
sendJson<{ names: string[] }>({ ... });
API
JsonArray
An array of Json
values.
import { JsonArray } from '@bitty/json';
const answers: JsonArray = [false, 'Okay', null, { color: '#fff' }, [0,3]];
JsonObject
An object whose property keys are strings and values are Json
values.
import { JsonObject } from '@bitty/json';
const response: JsonObject = {
id: 36,
association: null,
colors: [{color: '#00f'}, {color: '#d7a'}],
isDisabled: true
};
Json
A union of null
, boolean
, number
, string
, JsonArray
and JsonObject
types.
import { Json } from '@bitty/json';
const response: Json = {
latest: undefined,
current: [
{
name: 'Orange',
color: '#ff8721',
score: 2871,
disabled: true,
}
]
};
parseJson
Converts a valid JSON string into a value, whose type that extends Json
.
import { parseJson } from '@bitty/json';
type User = {
name: string;
};
const user = parseJson<User>('{"name":"Carlos Marcos"}');
toJson
Converts a value, whose type extends Json
, to value to JSON string.
import { toJson } from '@bitty/json';
type User = {
name: string;
};
const user = toJson<User>({
name: 'Carlos Marcos'
}, 0);
License
Released under MIT License.