Javascript JSON serializer Principal support

window.JSON doesn’t support Principals, and I’m wondering if anyone has taken it upon themselves to patch that, write a new serializer, or otherwise come up with a good solution!

A quick search didn’t turn anything up, so apologies if this is a duplicate.

Do the fromText and toText methods here help?

1 Like

I’m sure they do, yeah. For some context, I’m storing things in local storage and finding Principals revived from that store no longer behave correctly. Luckily the JSON base de/serialize methods provide an API to customize behaviour. Working on a little something rn. Thanks Paul!

This does the trick for me.

export function serialize(value: unknown): string {
    return JSON.stringify(value, (key, value) => {
        if (value?._isPrincipal) {
            const principal = {
                _isPrincipal: true,
                value: value.toText(),
            }
            console.log('serialized principal', principal);
            return principal;
        }
        return value;
    });
}

export function deserialize(text: string): unknown {
    return JSON.parse(text, (key, value) => {
        if (value?._isPrincipal) {
            const principal = Principal.fromText(value.value);
            console.log('rebuilt principal', principal);
            return principal;
        }
        return value;
    });
}
1 Like

Hi,

I use Text/String of Principal so

from Motoko to Javascript I use Principal.toText(x) and from Javascript to Motoko on Motoko side Principal.fromText(x)

1 Like