serialization.md (1972B)
1 # Serialization 2 3 Math.js has a number of data types like `Matrix`, `Complex`, and `Unit`. These 4 types are instantiated JavaScript objects. To be able to store these data types 5 or send them between processes, they must be serialized. The data types of 6 math.js can be serialized to JSON. Use cases: 7 8 - Store data in a database or on disk. 9 - Interchange of data between a server and a client. 10 - Interchange of data between a web worker and the browser. 11 12 Math.js types can be serialized using JavaScript's built-in `JSON.stringify` 13 function: 14 15 ```js 16 const x = math.complex('2 + 3i') 17 const str = JSON.stringify(x, math.replacer) 18 console.log(str) 19 // outputs a string '{"mathjs":"Complex","re":2,"im":3}' 20 ``` 21 22 > IMPORTANT: in most cases works, serialization correctly without 23 > passing the `math.replacer` function as second argument. This is because 24 > in most cases we can rely on the default behavior of JSON.stringify, which 25 > uses the `.toJSON` method on classes like `Unit` and `Complex` to correctly 26 > serialize them. However, there are a few special cases like the 27 > number `Infinity` which does require the replacer function in order to be 28 > serialized without losing information: without it, `Infinity` will be 29 > serialized as `"null"` and cannot be deserialized correctly. 30 > 31 > So, it's best to always pass the `math.replacer` function to prevent 32 > weird edge cases. 33 34 In order to deserialize a string, containing math.js data types, `JSON.parse` 35 can be used. In order to recognize the data types of math.js, `JSON.parse` must 36 be called with the reviver function of math.js: 37 38 ```js 39 const json = '{"mathjs":"Unit","value":5,"unit":"cm","fixPrefix":false}' 40 const x = JSON.parse(json, math.reviver) // Unit 5 cm 41 ``` 42 43 Note that if math.js is used in conjunction with other data types, it is 44 possible to use multiple reviver functions at the same time by cascading them: 45 46 ```js 47 const reviver = function (key, value) { 48 return reviver1(key, reviver2(key, value)) 49 } 50 ```