Special method ‣ toJSON() - chung-leong/zigar GitHub Wiki
This method is called when
JSON.stringify()
is used on an object. It behaves mostly like valueOf()
except for treatment of error
objects and big integers. While valueOf()
returns these as-is, toJSON()
tries to make them fit
the JSON format. Errors are converted to { error: "[MESSAGE]" }
. Big integers, provided that
they're between
Number.MIN_SAFE_INTEGER
and
Number.MAX_SAFE_INTEGER
,
are converted to regular numbers:
const JediError = error{ fell_to_the_dark_side, lightsaber_low_battery };
const JediStruct = struct {
age: u64 = 72,
err: JediError = JediError.fell_to_the_dark_side,
};
pub const jedi: JediStruct = .{};
import { jedi } from './tojson-example-1.zig';
console.log(jedi.valueOf());
console.log(jedi.toJSON());
{ age: 72n, err: [Error: Fell to the dark side] { number: 169 } }
{ age: 72, err: { error: 'Fell to the dark side' } }