Búsqueda de sitios web

javascript - Cómo analizar datos JSON (tipo: BigInt) en TypeScript


Tengo una solicitud simple, pero parece ser más difícil de lo esperado. Tengo que analizar un bigint desde un flujo JSON. El valor es 990000000069396215. En mi código, este valor se declara en TypeScript así: id_address: bigint. Pero esto no funciona, el valor se trunca y devuelve algo como 9900000000693962100

¿Cómo puedo manejar simplemente este bigint en mi código?

Respuesta #1

Si quieres que sea confiable y limpio, entonces siempre convierte a cadena/analiza los valores bigint como objetos:

function replacer( key: string, value: any ): any {
    if ( typeof value === 'bigint' ) {
        return { '__bigintval__': value.toString() };
    }
    return value;
}

function reviver( key: string, value: any ): any {
    if ( value != null && typeof value === 'object' && '__bigintval__' in value ) {
        return BigInt( value[ '__bigintval__' ] );
    }
    return value;
}

JSON.stringify( obj, replacer );

JSON.parse( str, reviver );

Respuesta #2

Supongo que necesitas hacer algo así,

export interface Address {
id_address: string;
}

Entonces en algún lugar de tu código donde implementes esta interfaz necesitas hacer,

const value = BigInt(id_address);  // I am guessing that inside your class you have spread your props and you can access id_address. So inside value you will get your Big integer value.

Referencia para BigInt.

Artículos relacionados