UNPKG

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