josdejong / josdejong/mathjs

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

Open
#3,562 10 comments 0 reactions 0 assignees View on GitHub
bug help wanted
Dominant language
JavaScript
Stars
15.1k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

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:

```js
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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.