Hi,
The reviver option in JSON.parse is very helpful. But, I am not sure how to deal with Infinity. At present, I am loosing its information. Here is an example:
var a="[1,2i,1/0]";
var b=math.evaluate(a);
var c = JSON.stringify(b);
var d = JSON.parse(c, math.json.reviver);
By the time I reach last step, the variable d is losing its Infinity value.
How can I fix this problem?
Thank you for your time.
_Originally posted by @skgadi in https://github.com/josdejong/mathjs/issues/27#issuecomment-621639696_
Thanks for reporting Suresh, this is a very good point.
So basically, the serialization should somehow serialize these special numeric values, so they can be revived correctly:
const aOriginal = Infinity
const stringified = JSON.stringify(aOriginal) // is '"null"'
const aRevived = JSON.parse(stringified, math.json.reviver)// is null, should be Infinity
assert.strictEqual(aOriginal, aRevived) // is false, should be true
The difficulty is that this is behavior of the JavaScript number type and the built-in stringifier JSON.stringify for which we want different behavior.
A possible solution would be to implement a JSON replace function, which turns numbers with a special value like Infinity into a special stringified object. Something like:
const aOriginal = Infinity
const stringified = JSON.stringify(aOriginal, math.json.replacer)
// '{"mathjs":"number","value":"Infinity"}'
const aRevived = JSON.parse(stringified, math.json.reviver)
assert.strictEqual(aOriginal, aRevived) // true
I created a fix in 28b7a02f01c6f4d4512c7f967ff9671e732d1220 (not yet published)
Thank you for resolving it real quick.
I will wait for the next release to include it in my project.
Fixed now in v6.6.5
Thank you. 馃憤