Skip to content

To & From JSON

Bertrand Laporte edited this page Jan 11, 2019 · 1 revision

Hibe provides 2 methods to load or convert datasets from a JavaScript Object

Load a dataset from a JavaScript object

Datasets can be created from JavaScript through the load function: load<T>(json: Object, c: Constructor<T> | Factory<T>):T Examples:

let tn = load({ value: "v2", node: { value: "v3", node: { value: "v4" } } }, TestNode);
let l = load(json = [{ value: "a" }, null, { value: "c" }], list(TestNode));
let m = load({ a: { value: "a" }, c: { value: "c" } }, map(TestNode));

Convert a dataset to a JavaScript object

Conversely datasets can be converted to JS through the convert function: function convert(d: any, converter?: JSConverter): any Examples:

@Dataset 
class TestNode {
    @value() value = "v1";
    @dataset(TestNode) node: TestNode; 
    @dataset(TestNode, false) node2: TestNode | undefined; 
}
let tn1 = new TestNode(), tn2 = new TestNode(), tn3 = new TestNode();
tn2.value = "v2";
tn3.value = "v3";
tn1.node = tn2;
tn2.node = tn3;
tn2.node2 = tn3;

assert.deepEqual(convert(tn1), {
    value: "v1",
    node: {
        value: "v2",
        node: { value: "v3" },
        node2: { value: "v3" }
    }
}, "convert tn1");

Custom conversion

Convert accepts a second converter argument which allows to precisely define how the object should be converted

export interface JSConversionContext {
    UNDEFINED: {},
    simpleTypeProps(): string[];
    datasetProps(): string[];
    getPropValue(propName): any;
    getDefaultConversion(): any;
    getPreviousConversion(): any;
}

export interface JSConverter {
    (obj: any, cc: JSConversionContext): any;
}

Example

let tn1 = new TestNode(), tn2 = new TestNode(), tn3 = new TestNode();
tn2.value = "v2";
tn3.value = "v3";
tn1.node = tn2;
tn2.node = tn3;
tn2.node2 = tn3;

function c(o: any, cc: JSConversionContext) {
    if (o.constructor === TestNode) {
        if (o.value === "v3") {
            return "tn3";
        } else if (o.value === "v2") {
            let r = cc.getDefaultConversion();
            r.isV2 = true;
            return r;
        } else {
            return cc.getDefaultConversion();
        }
    }
}

assert.deepEqual(convert(tn1, c), {
    value: "v1",
    node: {
        value: "v2",
        isV2: true,
        node: "tn3",
        node2: "tn3"
    }
}, "convert tn1");

Clone this wiki locally