我在 json 中有一些數字會溢位 Number 型別,所以我希望它是 bigint,但是如何呢?
{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}
uj5u.com熱心網友回復:
如果您有一些條件來確定應該將哪些數字視為BigInt(例如,數字大于1e10),您可以使用JSON.parse( reviver)的第二個引數:
const input = `{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}`,
output = JSON.parse(
input,
(_, value) =>
typeof value === 'number' && value > 1e10
? BigInt(value)
: value
)
console.log(typeof output.bar[0][0])
uj5u.com熱心網友回復:
您可以在 JSON.parse 中使用回呼函式來處理數字。
甲BigInt有值,也有時只是稱為一個BIGINT,是一個BIGINT原始的,乘n附加到一個整數文字的端部產生,或通過呼叫BigInt有()構造(但沒有新運營商),并給予它一個整數值或字串值。
const json = '{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}'
const data = JSON.parse(json, (_, v) =>
typeof v == "number" ? BigInt(v) : v
);
console.log(typeof data.foo[0][0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/327260.html
標籤:javascript json
下一篇:Kotlin密封介面序列化
