javascript - 如何在 TypeScript 中解析 JSON 數據(類型:BigInt)
我有一個簡單的請求,但它似乎比預期的更困難。我必須從 JSON 流中解析一個 bigint。該值是 990000000069396215。在我的程式碼中,這個值在 TypeScript 中宣告如下:id_address: bigint。但是這不起作用,該值被截斷,並且返回的值像 9900000000693962100 一樣不正確。
我如何在程式碼中簡單地管理這個 bigint?
答案#1
如果你想讓它可靠且乾淨,則應始終將 bigint 值作為物件進行字串化/解析:
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 );
答案#2
我猜你需要做類似這樣的事情,
export interface Address {
id_address: string;
}
然後在你的程式碼中某個實現此介面的地方,你需要這樣做,
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.
BigInt 的參考資料。
