gpt4 book ai didi

javascript - 如何使 JSON.parse() 将所有数字都视为 BigInt?

转载 作者:行者123 更新时间:2023-12-02 16:05:04 25 4
gpt4 key购买 nike

我在 json 中有一些数字溢出了 Number 类型,所以我希望它是 bigint,但是如何呢?

{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}

最佳答案

长篇小说;

您可以使用 JSON.parse() reviver参数

详细解决方案

要以这种方式控制 JSON.parse() 行为,您可以使用 JSON.parse 的第二个参数 ( reviver ) - pre - 处理键值对(并可能将所需值传递给 BigInt() )。

然而,识别为数字的值仍将被强制转换(查明此问题的功劳归功于@YohanesGultom)。

为了解决这个问题,您可以在源 JSON 字符串中引用您的大数字(将它们变成字符串),以便在转换为 bigint 时保留它们的值>.

只要您希望仅将某些数字转换为 bigint,您就需要选择适当的标准(例如,检查值是否超过 Number.MAX_SAFE_INTEGER Number.isSafeInteger(),正如@PeterSeliger 所建议的那样)。

因此,您的问题可能会通过以下方式解决:

// source JSON string

const input = `{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}`


// function that implements desired criteria
// to separate *big numbers* from *small* ones
//
// (works for input parameter num of type number/string)

const isBigNumber = num => !Number.isSafeInteger(+num)


// function that enquotes *big numbers* matching
// desired criteria into double quotes inside
// JSON string
//
// (function checking for *big numbers* may be
// passed as a second parameter for flexibility)

const enquoteBigNumber = (jsonString, bigNumChecker) =>
jsonString
.replaceAll(
/([:\s\[,]*)(\d+)([\s,\]]*)/g,
(matchingSubstr, prefix, bigNum, suffix) =>
bigNumChecker(bigNum)
? `${prefix}"${bigNum}"${suffix}`
: matchingSubstr
)


// parser that turns matching *big numbers* in
// source JSON string to bigint

const parseWithBigInt = (jsonString, bigNumChecker) =>
JSON.parse(
enquoteBigNumber(jsonString, bigNumChecker),
(key, value) =>
!isNaN(value) && bigNumChecker(value)
? BigInt(value)
: value
)

// resulting output

const output = parseWithBigInt(input, isBigNumber)


console.log("output.foo[1][0]: \n", output.foo[1][0], `(type: ${typeof output.foo[1][0]})`)
console.log("output.bar[0][0]: \n", output.bar[0][0].toString(), `(type: ${typeof output.bar[0][0]})`)
.as-console-wrapper{min-height: 100% !important;}

Note: you may find RegExp pattern to match strings of digits among JSON values not quite robust, so feel free to come up with yours (as mine was the quickest I managed to pick off the top of my head for demo purposes)

Note: you may still opt in for some library, as it was suggested by @YohanesGultom, yet adding 10k to your client bundle or 37k to your server-side dependencies (possibly, to docker image size) for that sole purpose may not be quite reasonable.

关于javascript - 如何使 JSON.parse() 将所有数字都视为 BigInt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69644298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com