assemblyscript-json
JSON encoder / decoder for AssemblyScript.
Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript.
Installation
assemblyscript-json
is available as a npm package. You can install assemblyscript-json
in your AssemblyScript project by running:
npm install --save assemblyscript-json
Usage
Parsing JSON
import { JSON } from "assemblyscript-json";
let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}'));
let worldOrNull: JSON.Str | null = jsonObj.getString("hello");
if (worldOrNull != null) {
let world: string = worldOrNull.valueOf();
}
let numOrNull: JSON.Num | null = jsonObj.getNum("value");
if (numOrNull != null) {
let value: f64 = numOrNull.valueOf();
}
let valueOrNull: JSON.Value | null = jsonObj.getValue("hello");
if (valueOrNull != null) {
let value = <JSON.Value>valueOrNull;
if(value.isString) {
let innerString = (<JSON.Str>value).valueOf();
let jsonString = (<JSON.Str>value).stringify();
}
}
Encoding JSON
import { JSONEncoder } from "assemblyscript-json";
let encoder = new JSONEncoder();
encoder.pushObject("obj");
encoder.setInteger("int", 10);
encoder.setString("str", "");
encoder.popObject();
let json: Uint8Array = encoder.serialize();
let jsonString: string = encoder.stringify();
assert(jsonString, '"obj": {"int": 10, "str": ""}');
Custom JSON Deserializers
import { JSONDecoder, JSONHandler } from "assemblyscript-json";
class MyJSONEventsHandler extends JSONHandler {
setString(name: string, value: string): void {
}
setBoolean(name: string, value: bool): void {
}
setNull(name: string): void {
}
setInteger(name: string, value: i64): void {
}
setFloat(name: string, value: f64): void {
}
pushArray(name: string): bool {
return true;
}
popArray(): void {
}
pushObject(name: string): bool {
return true;
}
popObject(): void {
}
}
let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler());
let jsonString = '{"hello": "world"}';
let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString));
decoder.deserialize(jsonBuffer);
Feel free to look through the tests for more usage examples.
Reference Documentation
Reference API Documentation can be found in the docs directory.
License
MIT