UNPKG

528 BJavaScriptView Raw
1// load math.js (using node.js)
2const math = require('../index')
3
4// serialize a math.js data type into a JSON string
5const x = math.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, math.json.reviver)
14console.log(math.typeof(y)) // 'Unit'
15console.log(y.toString()) // 5 cm