josdejong/mathjs

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

Open

#3562 aperta il 22 ott 2025

Vedi su GitHub
 (10 commenti) (0 reazioni) (0 assegnatari)JavaScript (1298 fork)batch import
bughelp wanted

Metriche repository

Star
 (13.832 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

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.

Guida contributor