UNPKG

526 BJavaScriptView Raw
1// load math.js (using node.js)
2const { complex, reviver, typeOf } = require('..')
3
4// serialize a math.js data type into a JSON string
5const x = complex('2+3i')
6const str1 = JSON.stringify(x)
7console.log(str1)
8// outputs {"mathjs":"Complex","re":2,"im":3}
9
10// deserialize a JSON string into a math.js data type
11// note that the reviver of math.js is needed for this:
12const str2 = '{"mathjs":"Unit","value":5,"unit":"cm"}'
13const y = JSON.parse(str2, reviver)
14console.log(typeOf(y)) // 'Unit'
15console.log(y.toString()) // 5 cm