Here is my request:
axios.get(url)
.then(res => {
console.log(res.data)
})
The output is { value: 156144277082605255 }
But should be { value: 156144277082605250 }
How to deal with Big Integers in this case? I tried to use json-bigint But since I am getting response.data from axios as object - it doesn't help.
Here is my request:
axios.get(url)
.then(res => {
console.log(res.data)
})
The output is { value: 156144277082605255 }
But should be { value: 156144277082605250 }
How to deal with Big Integers in this case? I tried to use json-bigint But since I am getting response.data from axios as object - it doesn't help.
Share Improve this question asked May 4, 2017 at 15:57 kurumkankurumkan 2,7254 gold badges35 silver badges56 bronze badges3 Answers
Reset to default 10My colleague answered the question:
I had to transform my response.data into string. (you may wonder - why the useless function - just to redefine default behavior, which parses string into object with JSON.parse - in here we skip this step)
axios.get(url, { transformResponse: [data => data] });
and then parse with json-bigint
JSONBigInt.parse(res.data);
Adding to the above answers, how to integrate JSONbigint with axios request and response interceptors.
import JSONbigint from 'json-bigint'
...
// request interceptor, preventing the response the default behaviour of parsing the response with JSON.parse
axios.interceptors.request.use((request) => {
request.transformResponse = [data => data]
return request
})
// response interceptor parsing the response data with JSONbigint, and returning the response
axios.interceptors.response.use((response) => {
response.data = JSONbigint.parse(response.data)
return response
}
Integers that are within the range will remain of type number
and those exceeding the range will be of type BigNumber
. One could additionally parse BigNumber
to string
if required by simply calling toString()
on the keys of type BigNumber
Run this to install json-bigint: npm install json-bigint --save
Then, use the transformResponse as an option of the axios get request
const jsonBig = require('json-bigint');
let url = 'https://your-api';
axios.get(url, { transformResponse: function(response) {
return jsonBig().parse(response.data);
}});
You can also use this in the following way:
const jsonBig = require('json-bigint');
axios({
url: 'https://your-api',
method: 'get',
transformResponse: function(response) {
return jsonBig().parse(response);
},
})