Skip to content
This repository has been archived by the owner on Oct 10, 2019. It is now read-only.

Consider mapping BigInt to String for JSON stringify #146

Closed
Eccenux opened this issue Apr 30, 2018 · 3 comments
Closed

Consider mapping BigInt to String for JSON stringify #146

Eccenux opened this issue Apr 30, 2018 · 3 comments

Comments

@Eccenux
Copy link

Eccenux commented Apr 30, 2018

Description

Current implementation (in Chrome) throws on BigInt strinigify:

JSON.stringify({a:123n})

VM97:1 Uncaught TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)

I think it would make sens if a string mapping would be provided (similar to Date mapping provided with date.toISOString() method).

Example

This is an example and that currently works:

JSON.stringify({a:123n, b:{c:12n}}, function(key, value){
	if (typeof value === 'bigint') {
		return value.toString() + "n";
	} else {
		return value;
	}
});

It produces a valid(!) JSON:

"{"a":"123n","b":{"c":"12n"}}"

A parser could then be provided to recognize and parse BigInt if required.

@bakkot
Copy link
Contributor

bakkot commented Apr 30, 2018

See discussion in #24.

I don't think outputting a string is a good default behavior here, since it would not (and cannot) parse back to a BigInt. You can of course trivially make stringify do the thing you want already, as you've pointed out.

@Eccenux
Copy link
Author

Eccenux commented Apr 30, 2018

Oh. Didn't realize implementing toJSON on BigInt is already supported. Never mind then :-). And thanks.

@Eccenux Eccenux closed this as completed Apr 30, 2018
@kaizhu256
Copy link

@bakkot, there's prior art for allowing JSON.stringify (to string mapping), but not JSON.parse with Date-objects.

figuring out how to idiot-proof serializing and passing-around 64bit integers to-and-fro
browser <-> server <-> databases
is a big enough industry-painpoint in my mind, that BigInt should try to address it in some form.

even without JSON.parse, having a standardized JSON.stringify for BigInt to plain-strings, would still be tremendously helpful in industry by having everyone agree to a common serialization format.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants