JavaScript解析JSON时数字精度丢失问题求助(node-fetch场景)
Hey there! I totally get where you're coming from—dealing with JavaScript's number precision limits can be super frustrating, especially when you need exact IDs from an API. Let's break down why this is happening and how to fix it.
The Root Cause
JavaScript uses 64-bit floating point numbers (the Number type), which can only represent integers precisely up to 2^53 (that's 9007199254740992). Your ID 1575890170351016059 is way larger than that, so when Node.js parses it into a Number, it gets rounded to the nearest representable value (1575890170351016000 in your case).
As for where node-fetch is doing this: when you call response.json(), it internally reads the raw response text and runs JSON.parse() on it. The default JSON.parse() converts numeric values in the JSON into JavaScript Numbers—this is exactly where the precision loss happens.
The Solution
Instead of letting response.json() handle parsing automatically, we'll take control of the process to preserve the exact ID value. Here's how:
1. Parse the raw text with a custom reviver function
First, fetch the raw text of the response, then use JSON.parse() with a reviver function that converts the id field to a string instead of a Number:
async function fetchApiData() { const response = await fetch('your-api-endpoint-url'); // Get the raw response text instead of parsing directly to JSON const rawText = await response.text(); // Parse with a reviver to handle the big ID const data = JSON.parse(rawText, (key, value) => { // Check if the current key is 'id' and the value is a number if (key === 'id' && typeof value === 'number') { // Convert it to a string to preserve full precision return value.toString(); } // Return all other values as-is return value; }); console.log(data.id); // This will now show the exact ID: 1575890170351016059 }
2. Bonus: If the API supports it, request string IDs
If you have control over the API or it offers a configuration option, ask for the id to be returned as a string in the JSON response. This avoids the parsing issue entirely, since strings can hold arbitrarily long numeric values.
Why This Works
By skipping response.json() and parsing the raw text ourselves, we intercept the conversion of the id field before it becomes a lossy Number. Converting it to a string ensures every digit is preserved exactly.
内容的提问来源于stack exchange,提问作者Sachin

