Right now I'm getting a weird error, I'm trying to convert an object to a string and I get this type error.
const x = await web3.eth.getTransaction(tx);
console.log(x);
^
Console Output:
{
blockHash: '0x000ef0000abf000d0f000e0ff000c000a00d750d066ea0c60a00f0000b0f000c0',
blockNumber: 0n,
from: '0x0c000f0e0c000e000bfbc0c002000c0b0ec100000',
gas: 0n,
gasPrice: 0n,
maxFeePerGas: 0n,
maxPriorityFeePerGas: 0n,
hash: '0x000000000000000d00f000f0000ffa000bd000c00cc0000b0fd000a0a00ffccfc',
input: '0x',
nonce: 0n,
to: '0x000d0aa0fa0000ef00b00cb0e0000d000c0a00e0',
transactionIndex: 0n,
value: 0n,
type: 0n,
accessList: [],
chainId: 0n,
v: 0n,
r: '0xa0000f00000f00c0b000000bffc000000000a000000000cc00e000100aa0d0d0',
s: '0x0c0f00ec0cf0df0eb0000e00bce0000d00b0000a0000ffae0cc0ef28000e0cc',
data: '0x'
}
But then I try to convert x
into a string:
JSON.stringify(recoverTransaction)
^
TypeError: Do not know how to serialize a BigInt
Right now I'm getting a weird error, I'm trying to convert an object to a string and I get this type error.
const x = await web3.eth.getTransaction(tx);
console.log(x);
^
Console Output:
{
blockHash: '0x000ef0000abf000d0f000e0ff000c000a00d750d066ea0c60a00f0000b0f000c0',
blockNumber: 0n,
from: '0x0c000f0e0c000e000bfbc0c002000c0b0ec100000',
gas: 0n,
gasPrice: 0n,
maxFeePerGas: 0n,
maxPriorityFeePerGas: 0n,
hash: '0x000000000000000d00f000f0000ffa000bd000c00cc0000b0fd000a0a00ffccfc',
input: '0x',
nonce: 0n,
to: '0x000d0aa0fa0000ef00b00cb0e0000d000c0a00e0',
transactionIndex: 0n,
value: 0n,
type: 0n,
accessList: [],
chainId: 0n,
v: 0n,
r: '0xa0000f00000f00c0b000000bffc000000000a000000000cc00e000100aa0d0d0',
s: '0x0c0f00ec0cf0df0eb0000e00bce0000d00b0000a0000ffae0cc0ef28000e0cc',
data: '0x'
}
But then I try to convert x
into a string:
JSON.stringify(recoverTransaction)
^
TypeError: Do not know how to serialize a BigInt
Share
Improve this question
edited Mar 24 at 1:27
Teyrox
asked Mar 24 at 1:21
TeyroxTeyrox
3132 silver badges10 bronze badges
2
|
1 Answer
Reset to default 1I solved with this function:
- Checks if the value is of type bigint and converts it to a string using
value.toString()
. - Non-bigint values remain unchanged.
JSON.stringify(x, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
);
The transaction object is now successfully serialized as a JSON string, with all BigInt
values represented as strings.
BigInt
is not one of the valid JSON datatypes, you can't useJSON.stringify()
to convert it to a string. – Barmar Commented Mar 24 at 1:24