serialization.js (626B)
1 // load math.js (using node.js) 2 const { 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 6 const x = complex('2+3i') 7 const str1 = JSON.stringify(x, replacer) 8 console.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: 13 const str2 = '{"mathjs":"Unit","value":5,"unit":"cm"}' 14 const y = JSON.parse(str2, reviver) 15 console.log(typeOf(y)) // 'Unit' 16 console.log(y.toString()) // 5 cm