[英]How to parse a JSON data (type : BigInt) in TypeScript
I have a simple request but It seems to be harder than expected.我有一个简单的要求,但似乎比预期的要难。 I have to parse a
bigint
from a JSON stream.我必须从 JSON stream 中解析一个
bigint
。 The value is 990000000069396215
.该值为
990000000069396215
。 In my code, this value is declared in TypeScript like this: id_address: bigint
.在我的代码中,这个值在 TypeScript 中声明,如下所示:
id_address: bigint
。 But this is not working, the value is truncated, and return nothing like 9900000000693962100
但这不起作用,该值被截断,并且不返回
9900000000693962100
How can I simply manage this bigint
in my code?我怎样才能在我的代码中简单地管理这个
bigint
?
I guess you need to do something like this,我想你需要做这样的事情,
export interface Address {
id_address: string;
}
Then somewhere in your code where you implement this interface you need to do,然后在你的代码中的某个地方实现你需要做的这个接口,
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.
If you want to make it reliable and clean then always stringify/parse bigint values as objects:如果你想让它可靠和干净,那么总是将 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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.