UNPKG

1.97 kBMarkdownView Raw
1# Serialization
2
3Math.js has a number of data types like `Matrix`, `Complex`, and `Unit`. These
4types are instantiated JavaScript objects. To be able to store these data types
5or send them between processes, they must be serialized. The data types of
6math.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
12Math.js types can be serialized using JavaScript's built-in `JSON.stringify`
13function:
14
15```js
16const x = math.complex('2 + 3i')
17const str = JSON.stringify(x, math.replacer)
18console.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
34In order to deserialize a string, containing math.js data types, `JSON.parse`
35can be used. In order to recognize the data types of math.js, `JSON.parse` must
36be called with the reviver function of math.js:
37
38```js
39const json = '{"mathjs":"Unit","value":5,"unit":"cm","fixPrefix":false}'
40const x = JSON.parse(json, math.reviver) // Unit 5 cm
41```
42
43Note that if math.js is used in conjunction with other data types, it is
44possible to use multiple reviver functions at the same time by cascading them:
45
46```js
47const reviver = function (key, value) {
48 return reviver1(key, reviver2(key, value))
49}
50```