josdejong/mathjs

Cannot always parse a unit deserialized from JSON via the expression parser

Open

#3,562 创建于 2025年10月22日

在 GitHub 查看
 (10 评论) (0 反应) (0 负责人)JavaScript (13,832 star) (1,298 fork)batch import
bughelp wanted

描述

From discussion https://github.com/josdejong/mathjs/discussions/3031#discussioncomment-14692393

When formatting a unit, it is not always possible to parse it via the expression parser when it was revived from JSON data.

Example:

const unit1 = math.evaluate('t=9cm * 7in^2')
console.log('unit1', unit1.toString())
// "24.803149606299215 in^3"

const data = JSON.stringify(unit1, math.replacer)
console.log('data', data)
// {"mathjs":"Unit","value":63,"unit":"cm in^2","fixPrefix":false}

const unit2 = JSON.parse(data, math.reviver)
console.log('unit2', unit2.toString())
// "63 cm in^2"

console.log(math.parse(unit2.toString()));
// SyntaxError: Value expected (char 9)

The outcome 63 cm in^2 is technically correct, but the parser cannot parse this due to a conflict with in interpreted as the unit conversion operator a in b instead of the unit inch.

It looks like serializing and reviving either loses some of the original information, since after deserialization the .toString() method gives a different outcome.

Maybe we should normalize the unit before serialization, or add additional state ensuring that the unit .toString() gives the same output as the original.

贡献者指南