UNPKG

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