1

I have an API returning some JSON and one of the fields is a big integer:

{
  "id": 828845277259899344,
  "name": "Joe",
  "email": "joe@example.com",
  ...
}

When getting the data with await response.json(), the id is being converted to 828845277259899400. I understand JS can't handle integers that big but I was hoping I could get it as a string instead. Tried to find my way using BigInt but still not there. I couldn't find the answer in similar question here either.

proko
  • 175
  • 2
  • 11
  • 5
    The API will have to make it a string in the JSON; once it's parsed at the client it's too late. – Pointy Nov 08 '20 at 16:54
  • 1
    You could extract the value from the raw json and pass the resulting string to BigInt – Patrick Evans Nov 08 '20 at 16:57
  • If I get the json with `response.text()` instead I can see the id is still correct thats why I thought it was not too late. But really don't like the idea of parsing the json as string and extracting the id form it. How would you extract the value Patrick? – proko Nov 08 '20 at 17:02
  • 1
    There are some packages that allow parsing JSON with BigInt values like [this one](https://www.npmjs.com/package/json-bigint) and there is also [a proposal](https://github.com/tc39/proposal-json-parse-with-source) to enable parsing with source, so you can do the formatting yourself. However, the proposal is still at stage 2. Getting a library might be the easier option right now. – VLAZ Nov 08 '20 at 17:06
  • 1
    if it is just that one item, You could use a regex, ie `str.match(/"id":\s?(\d+),/)`. If more you could use the regex `matchAll()` method but would require extra code to match the value to each item – Patrick Evans Nov 08 '20 at 17:11

0 Answers0