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)
|
18 | console.log(str)
|
19 | // outputs a string '{"mathjs":"Complex","re":2,"im":3}'
|
20 | ```
|
21 |
|
22 | In order to deserialize a string, containing math.js data types, `JSON.parse`
|
23 | can be used. In order to recognize the data types of math.js, `JSON.parse` must
|
24 | be called with the reviver function of math.js:
|
25 |
|
26 | ```js
|
27 | const json = '{"mathjs":"Unit","value":5,"unit":"cm","fixPrefix":false}'
|
28 | const x = JSON.parse(json, math.json.reviver) // Unit 5 cm
|
29 | ```
|
30 |
|
31 | Note that if math.js is used in conjunction with other data types, it is
|
32 | possible to use multiple reviver functions at the same time by cascading them:
|
33 |
|
34 | ```js
|
35 | const reviver = function (key, value) {
|
36 | return reviver1(key, reviver2(key, value))
|
37 | }
|
38 | ```
|